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

1.355   ! brouard     1: /* $Id: imach.c,v 1.354 2023/05/21 05:05:17 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.355   ! brouard     4:   Revision 1.354  2023/05/21 05:05:17  brouard
        !             5:   Summary: Temporary change for imachprax
        !             6: 
1.354     brouard     7:   Revision 1.353  2023/05/08 18:48:22  brouard
                      8:   *** empty log message ***
                      9: 
1.353     brouard    10:   Revision 1.352  2023/04/29 10:46:21  brouard
                     11:   *** empty log message ***
                     12: 
1.352     brouard    13:   Revision 1.351  2023/04/29 10:43:47  brouard
                     14:   Summary: 099r45
                     15: 
1.351     brouard    16:   Revision 1.350  2023/04/24 11:38:06  brouard
                     17:   *** empty log message ***
                     18: 
1.350     brouard    19:   Revision 1.349  2023/01/31 09:19:37  brouard
                     20:   Summary: Improvements in models with age*Vn*Vm
                     21: 
1.348     brouard    22:   Revision 1.347  2022/09/18 14:36:44  brouard
                     23:   Summary: version 0.99r42
                     24: 
1.347     brouard    25:   Revision 1.346  2022/09/16 13:52:36  brouard
                     26:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     27: 
1.346     brouard    28:   Revision 1.345  2022/09/16 13:40:11  brouard
                     29:   Summary: Version 0.99r41
                     30: 
                     31:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     32: 
1.345     brouard    33:   Revision 1.344  2022/09/14 19:33:30  brouard
                     34:   Summary: version 0.99r40
                     35: 
                     36:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     37: 
1.344     brouard    38:   Revision 1.343  2022/09/14 14:22:16  brouard
                     39:   Summary: version 0.99r39
                     40: 
                     41:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     42:   (fixed or time varying), using new last columns of
                     43:   ILK_parameter.txt file.
                     44: 
1.343     brouard    45:   Revision 1.342  2022/09/11 19:54:09  brouard
                     46:   Summary: 0.99r38
                     47: 
                     48:   * imach.c (Module): Adding timevarying products of any kinds,
                     49:   should work before shifting cotvar from ncovcol+nqv columns in
                     50:   order to have a correspondance between the column of cotvar and
                     51:   the id of column.
                     52:   (Module): Some cleaning and adding covariates in ILK.txt
                     53: 
1.342     brouard    54:   Revision 1.341  2022/09/11 07:58:42  brouard
                     55:   Summary: Version 0.99r38
                     56: 
                     57:   After adding change in cotvar.
                     58: 
1.341     brouard    59:   Revision 1.340  2022/09/11 07:53:11  brouard
                     60:   Summary: Version imach 0.99r37
                     61: 
                     62:   * imach.c (Module): Adding timevarying products of any kinds,
                     63:   should work before shifting cotvar from ncovcol+nqv columns in
                     64:   order to have a correspondance between the column of cotvar and
                     65:   the id of column.
                     66: 
1.340     brouard    67:   Revision 1.339  2022/09/09 17:55:22  brouard
                     68:   Summary: version 0.99r37
                     69: 
                     70:   * imach.c (Module): Many improvements for fixing products of fixed
                     71:   timevarying as well as fixed * fixed, and test with quantitative
                     72:   covariate.
                     73: 
1.339     brouard    74:   Revision 1.338  2022/09/04 17:40:33  brouard
                     75:   Summary: 0.99r36
                     76: 
                     77:   * imach.c (Module): Now the easy runs i.e. without result or
                     78:   model=1+age only did not work. The defautl combination should be 1
                     79:   and not 0 because everything hasn't been tranformed yet.
                     80: 
1.338     brouard    81:   Revision 1.337  2022/09/02 14:26:02  brouard
                     82:   Summary: version 0.99r35
                     83: 
                     84:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     85:   1+age+V1+V1*age for females and 1+age for females only
                     86:   (education=1 noweight)
                     87: 
1.337     brouard    88:   Revision 1.336  2022/08/31 09:52:36  brouard
                     89:   *** empty log message ***
                     90: 
1.336     brouard    91:   Revision 1.335  2022/08/31 08:23:16  brouard
                     92:   Summary: improvements...
                     93: 
1.335     brouard    94:   Revision 1.334  2022/08/25 09:08:41  brouard
                     95:   Summary: In progress for quantitative
                     96: 
1.334     brouard    97:   Revision 1.333  2022/08/21 09:10:30  brouard
                     98:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     99:   reassigning covariates: my first idea was that people will always
                    100:   use the first covariate V1 into the model but in fact they are
                    101:   producing data with many covariates and can use an equation model
                    102:   with some of the covariate; it means that in a model V2+V3 instead
                    103:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    104:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    105:   the equation model is restricted to two variables only (V2, V3)
                    106:   and the combination for V2 should be codtabm(k,1) instead of
                    107:   (codtabm(k,2), and the code should be
                    108:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    109:   made. All of these should be simplified once a day like we did in
                    110:   hpxij() for example by using precov[nres] which is computed in
                    111:   decoderesult for each nres of each resultline. Loop should be done
                    112:   on the equation model globally by distinguishing only product with
                    113:   age (which are changing with age) and no more on type of
                    114:   covariates, single dummies, single covariates.
                    115: 
1.333     brouard   116:   Revision 1.332  2022/08/21 09:06:25  brouard
                    117:   Summary: Version 0.99r33
                    118: 
                    119:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    120:   reassigning covariates: my first idea was that people will always
                    121:   use the first covariate V1 into the model but in fact they are
                    122:   producing data with many covariates and can use an equation model
                    123:   with some of the covariate; it means that in a model V2+V3 instead
                    124:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    125:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    126:   the equation model is restricted to two variables only (V2, V3)
                    127:   and the combination for V2 should be codtabm(k,1) instead of
                    128:   (codtabm(k,2), and the code should be
                    129:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    130:   made. All of these should be simplified once a day like we did in
                    131:   hpxij() for example by using precov[nres] which is computed in
                    132:   decoderesult for each nres of each resultline. Loop should be done
                    133:   on the equation model globally by distinguishing only product with
                    134:   age (which are changing with age) and no more on type of
                    135:   covariates, single dummies, single covariates.
                    136: 
1.332     brouard   137:   Revision 1.331  2022/08/07 05:40:09  brouard
                    138:   *** empty log message ***
                    139: 
1.331     brouard   140:   Revision 1.330  2022/08/06 07:18:25  brouard
                    141:   Summary: last 0.99r31
                    142: 
                    143:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    144: 
1.330     brouard   145:   Revision 1.329  2022/08/03 17:29:54  brouard
                    146:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    147: 
1.329     brouard   148:   Revision 1.328  2022/07/27 17:40:48  brouard
                    149:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    150: 
1.328     brouard   151:   Revision 1.327  2022/07/27 14:47:35  brouard
                    152:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    153: 
1.327     brouard   154:   Revision 1.326  2022/07/26 17:33:55  brouard
                    155:   Summary: some test with nres=1
                    156: 
1.326     brouard   157:   Revision 1.325  2022/07/25 14:27:23  brouard
                    158:   Summary: r30
                    159: 
                    160:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    161:   coredumped, revealed by Feiuno, thank you.
                    162: 
1.325     brouard   163:   Revision 1.324  2022/07/23 17:44:26  brouard
                    164:   *** empty log message ***
                    165: 
1.324     brouard   166:   Revision 1.323  2022/07/22 12:30:08  brouard
                    167:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    168: 
1.323     brouard   169:   Revision 1.322  2022/07/22 12:27:48  brouard
                    170:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    171: 
1.322     brouard   172:   Revision 1.321  2022/07/22 12:04:24  brouard
                    173:   Summary: r28
                    174: 
                    175:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    176: 
1.321     brouard   177:   Revision 1.320  2022/06/02 05:10:11  brouard
                    178:   *** empty log message ***
                    179: 
1.320     brouard   180:   Revision 1.319  2022/06/02 04:45:11  brouard
                    181:   * imach.c (Module): Adding the Wald tests from the log to the main
                    182:   htm for better display of the maximum likelihood estimators.
                    183: 
1.319     brouard   184:   Revision 1.318  2022/05/24 08:10:59  brouard
                    185:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    186:   of confidencce intervals with product in the equation modelC
                    187: 
1.318     brouard   188:   Revision 1.317  2022/05/15 15:06:23  brouard
                    189:   * imach.c (Module):  Some minor improvements
                    190: 
1.317     brouard   191:   Revision 1.316  2022/05/11 15:11:31  brouard
                    192:   Summary: r27
                    193: 
1.316     brouard   194:   Revision 1.315  2022/05/11 15:06:32  brouard
                    195:   *** empty log message ***
                    196: 
1.315     brouard   197:   Revision 1.314  2022/04/13 17:43:09  brouard
                    198:   * imach.c (Module): Adding link to text data files
                    199: 
1.314     brouard   200:   Revision 1.313  2022/04/11 15:57:42  brouard
                    201:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    202: 
1.313     brouard   203:   Revision 1.312  2022/04/05 21:24:39  brouard
                    204:   *** empty log message ***
                    205: 
1.312     brouard   206:   Revision 1.311  2022/04/05 21:03:51  brouard
                    207:   Summary: Fixed quantitative covariates
                    208: 
                    209:          Fixed covariates (dummy or quantitative)
                    210:        with missing values have never been allowed but are ERRORS and
                    211:        program quits. Standard deviations of fixed covariates were
                    212:        wrongly computed. Mean and standard deviations of time varying
                    213:        covariates are still not computed.
                    214: 
1.311     brouard   215:   Revision 1.310  2022/03/17 08:45:53  brouard
                    216:   Summary: 99r25
                    217: 
                    218:   Improving detection of errors: result lines should be compatible with
                    219:   the model.
                    220: 
1.310     brouard   221:   Revision 1.309  2021/05/20 12:39:14  brouard
                    222:   Summary: Version 0.99r24
                    223: 
1.309     brouard   224:   Revision 1.308  2021/03/31 13:11:57  brouard
                    225:   Summary: Version 0.99r23
                    226: 
                    227: 
                    228:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    229: 
1.308     brouard   230:   Revision 1.307  2021/03/08 18:11:32  brouard
                    231:   Summary: 0.99r22 fixed bug on result:
                    232: 
1.307     brouard   233:   Revision 1.306  2021/02/20 15:44:02  brouard
                    234:   Summary: Version 0.99r21
                    235: 
                    236:   * imach.c (Module): Fix bug on quitting after result lines!
                    237:   (Module): Version 0.99r21
                    238: 
1.306     brouard   239:   Revision 1.305  2021/02/20 15:28:30  brouard
                    240:   * imach.c (Module): Fix bug on quitting after result lines!
                    241: 
1.305     brouard   242:   Revision 1.304  2021/02/12 11:34:20  brouard
                    243:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    244: 
1.304     brouard   245:   Revision 1.303  2021/02/11 19:50:15  brouard
                    246:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    247: 
1.303     brouard   248:   Revision 1.302  2020/02/22 21:00:05  brouard
                    249:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    250:   and life table from the data without any state)
                    251: 
1.302     brouard   252:   Revision 1.301  2019/06/04 13:51:20  brouard
                    253:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    254: 
1.301     brouard   255:   Revision 1.300  2019/05/22 19:09:45  brouard
                    256:   Summary: version 0.99r19 of May 2019
                    257: 
1.300     brouard   258:   Revision 1.299  2019/05/22 18:37:08  brouard
                    259:   Summary: Cleaned 0.99r19
                    260: 
1.299     brouard   261:   Revision 1.298  2019/05/22 18:19:56  brouard
                    262:   *** empty log message ***
                    263: 
1.298     brouard   264:   Revision 1.297  2019/05/22 17:56:10  brouard
                    265:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    266: 
1.297     brouard   267:   Revision 1.296  2019/05/20 13:03:18  brouard
                    268:   Summary: Projection syntax simplified
                    269: 
                    270: 
                    271:   We can now start projections, forward or backward, from the mean date
                    272:   of inteviews up to or down to a number of years of projection:
                    273:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    274:   or
                    275:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    276:   or
                    277:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    278:   or
                    279:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    280: 
1.296     brouard   281:   Revision 1.295  2019/05/18 09:52:50  brouard
                    282:   Summary: doxygen tex bug
                    283: 
1.295     brouard   284:   Revision 1.294  2019/05/16 14:54:33  brouard
                    285:   Summary: There was some wrong lines added
                    286: 
1.294     brouard   287:   Revision 1.293  2019/05/09 15:17:34  brouard
                    288:   *** empty log message ***
                    289: 
1.293     brouard   290:   Revision 1.292  2019/05/09 14:17:20  brouard
                    291:   Summary: Some updates
                    292: 
1.292     brouard   293:   Revision 1.291  2019/05/09 13:44:18  brouard
                    294:   Summary: Before ncovmax
                    295: 
1.291     brouard   296:   Revision 1.290  2019/05/09 13:39:37  brouard
                    297:   Summary: 0.99r18 unlimited number of individuals
                    298: 
                    299:   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.
                    300: 
1.290     brouard   301:   Revision 1.289  2018/12/13 09:16:26  brouard
                    302:   Summary: Bug for young ages (<-30) will be in r17
                    303: 
1.289     brouard   304:   Revision 1.288  2018/05/02 20:58:27  brouard
                    305:   Summary: Some bugs fixed
                    306: 
1.288     brouard   307:   Revision 1.287  2018/05/01 17:57:25  brouard
                    308:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    309: 
1.287     brouard   310:   Revision 1.286  2018/04/27 14:27:04  brouard
                    311:   Summary: some minor bugs
                    312: 
1.286     brouard   313:   Revision 1.285  2018/04/21 21:02:16  brouard
                    314:   Summary: Some bugs fixed, valgrind tested
                    315: 
1.285     brouard   316:   Revision 1.284  2018/04/20 05:22:13  brouard
                    317:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    318: 
1.284     brouard   319:   Revision 1.283  2018/04/19 14:49:16  brouard
                    320:   Summary: Some minor bugs fixed
                    321: 
1.283     brouard   322:   Revision 1.282  2018/02/27 22:50:02  brouard
                    323:   *** empty log message ***
                    324: 
1.282     brouard   325:   Revision 1.281  2018/02/27 19:25:23  brouard
                    326:   Summary: Adding second argument for quitting
                    327: 
1.281     brouard   328:   Revision 1.280  2018/02/21 07:58:13  brouard
                    329:   Summary: 0.99r15
                    330: 
                    331:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    332: 
1.280     brouard   333:   Revision 1.279  2017/07/20 13:35:01  brouard
                    334:   Summary: temporary working
                    335: 
1.279     brouard   336:   Revision 1.278  2017/07/19 14:09:02  brouard
                    337:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    338: 
1.278     brouard   339:   Revision 1.277  2017/07/17 08:53:49  brouard
                    340:   Summary: BOM files can be read now
                    341: 
1.277     brouard   342:   Revision 1.276  2017/06/30 15:48:31  brouard
                    343:   Summary: Graphs improvements
                    344: 
1.276     brouard   345:   Revision 1.275  2017/06/30 13:39:33  brouard
                    346:   Summary: Saito's color
                    347: 
1.275     brouard   348:   Revision 1.274  2017/06/29 09:47:08  brouard
                    349:   Summary: Version 0.99r14
                    350: 
1.274     brouard   351:   Revision 1.273  2017/06/27 11:06:02  brouard
                    352:   Summary: More documentation on projections
                    353: 
1.273     brouard   354:   Revision 1.272  2017/06/27 10:22:40  brouard
                    355:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    356: 
1.272     brouard   357:   Revision 1.271  2017/06/27 10:17:50  brouard
                    358:   Summary: Some bug with rint
                    359: 
1.271     brouard   360:   Revision 1.270  2017/05/24 05:45:29  brouard
                    361:   *** empty log message ***
                    362: 
1.270     brouard   363:   Revision 1.269  2017/05/23 08:39:25  brouard
                    364:   Summary: Code into subroutine, cleanings
                    365: 
1.269     brouard   366:   Revision 1.268  2017/05/18 20:09:32  brouard
                    367:   Summary: backprojection and confidence intervals of backprevalence
                    368: 
1.268     brouard   369:   Revision 1.267  2017/05/13 10:25:05  brouard
                    370:   Summary: temporary save for backprojection
                    371: 
1.267     brouard   372:   Revision 1.266  2017/05/13 07:26:12  brouard
                    373:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    374: 
1.266     brouard   375:   Revision 1.265  2017/04/26 16:22:11  brouard
                    376:   Summary: imach 0.99r13 Some bugs fixed
                    377: 
1.265     brouard   378:   Revision 1.264  2017/04/26 06:01:29  brouard
                    379:   Summary: Labels in graphs
                    380: 
1.264     brouard   381:   Revision 1.263  2017/04/24 15:23:15  brouard
                    382:   Summary: to save
                    383: 
1.263     brouard   384:   Revision 1.262  2017/04/18 16:48:12  brouard
                    385:   *** empty log message ***
                    386: 
1.262     brouard   387:   Revision 1.261  2017/04/05 10:14:09  brouard
                    388:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    389: 
1.261     brouard   390:   Revision 1.260  2017/04/04 17:46:59  brouard
                    391:   Summary: Gnuplot indexations fixed (humm)
                    392: 
1.260     brouard   393:   Revision 1.259  2017/04/04 13:01:16  brouard
                    394:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    395: 
1.259     brouard   396:   Revision 1.258  2017/04/03 10:17:47  brouard
                    397:   Summary: Version 0.99r12
                    398: 
                    399:   Some cleanings, conformed with updated documentation.
                    400: 
1.258     brouard   401:   Revision 1.257  2017/03/29 16:53:30  brouard
                    402:   Summary: Temp
                    403: 
1.257     brouard   404:   Revision 1.256  2017/03/27 05:50:23  brouard
                    405:   Summary: Temporary
                    406: 
1.256     brouard   407:   Revision 1.255  2017/03/08 16:02:28  brouard
                    408:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    409: 
1.255     brouard   410:   Revision 1.254  2017/03/08 07:13:00  brouard
                    411:   Summary: Fixing data parameter line
                    412: 
1.254     brouard   413:   Revision 1.253  2016/12/15 11:59:41  brouard
                    414:   Summary: 0.99 in progress
                    415: 
1.253     brouard   416:   Revision 1.252  2016/09/15 21:15:37  brouard
                    417:   *** empty log message ***
                    418: 
1.252     brouard   419:   Revision 1.251  2016/09/15 15:01:13  brouard
                    420:   Summary: not working
                    421: 
1.251     brouard   422:   Revision 1.250  2016/09/08 16:07:27  brouard
                    423:   Summary: continue
                    424: 
1.250     brouard   425:   Revision 1.249  2016/09/07 17:14:18  brouard
                    426:   Summary: Starting values from frequencies
                    427: 
1.249     brouard   428:   Revision 1.248  2016/09/07 14:10:18  brouard
                    429:   *** empty log message ***
                    430: 
1.248     brouard   431:   Revision 1.247  2016/09/02 11:11:21  brouard
                    432:   *** empty log message ***
                    433: 
1.247     brouard   434:   Revision 1.246  2016/09/02 08:49:22  brouard
                    435:   *** empty log message ***
                    436: 
1.246     brouard   437:   Revision 1.245  2016/09/02 07:25:01  brouard
                    438:   *** empty log message ***
                    439: 
1.245     brouard   440:   Revision 1.244  2016/09/02 07:17:34  brouard
                    441:   *** empty log message ***
                    442: 
1.244     brouard   443:   Revision 1.243  2016/09/02 06:45:35  brouard
                    444:   *** empty log message ***
                    445: 
1.243     brouard   446:   Revision 1.242  2016/08/30 15:01:20  brouard
                    447:   Summary: Fixing a lots
                    448: 
1.242     brouard   449:   Revision 1.241  2016/08/29 17:17:25  brouard
                    450:   Summary: gnuplot problem in Back projection to fix
                    451: 
1.241     brouard   452:   Revision 1.240  2016/08/29 07:53:18  brouard
                    453:   Summary: Better
                    454: 
1.240     brouard   455:   Revision 1.239  2016/08/26 15:51:03  brouard
                    456:   Summary: Improvement in Powell output in order to copy and paste
                    457: 
                    458:   Author:
                    459: 
1.239     brouard   460:   Revision 1.238  2016/08/26 14:23:35  brouard
                    461:   Summary: Starting tests of 0.99
                    462: 
1.238     brouard   463:   Revision 1.237  2016/08/26 09:20:19  brouard
                    464:   Summary: to valgrind
                    465: 
1.237     brouard   466:   Revision 1.236  2016/08/25 10:50:18  brouard
                    467:   *** empty log message ***
                    468: 
1.236     brouard   469:   Revision 1.235  2016/08/25 06:59:23  brouard
                    470:   *** empty log message ***
                    471: 
1.235     brouard   472:   Revision 1.234  2016/08/23 16:51:20  brouard
                    473:   *** empty log message ***
                    474: 
1.234     brouard   475:   Revision 1.233  2016/08/23 07:40:50  brouard
                    476:   Summary: not working
                    477: 
1.233     brouard   478:   Revision 1.232  2016/08/22 14:20:21  brouard
                    479:   Summary: not working
                    480: 
1.232     brouard   481:   Revision 1.231  2016/08/22 07:17:15  brouard
                    482:   Summary: not working
                    483: 
1.231     brouard   484:   Revision 1.230  2016/08/22 06:55:53  brouard
                    485:   Summary: Not working
                    486: 
1.230     brouard   487:   Revision 1.229  2016/07/23 09:45:53  brouard
                    488:   Summary: Completing for func too
                    489: 
1.229     brouard   490:   Revision 1.228  2016/07/22 17:45:30  brouard
                    491:   Summary: Fixing some arrays, still debugging
                    492: 
1.227     brouard   493:   Revision 1.226  2016/07/12 18:42:34  brouard
                    494:   Summary: temp
                    495: 
1.226     brouard   496:   Revision 1.225  2016/07/12 08:40:03  brouard
                    497:   Summary: saving but not running
                    498: 
1.225     brouard   499:   Revision 1.224  2016/07/01 13:16:01  brouard
                    500:   Summary: Fixes
                    501: 
1.224     brouard   502:   Revision 1.223  2016/02/19 09:23:35  brouard
                    503:   Summary: temporary
                    504: 
1.223     brouard   505:   Revision 1.222  2016/02/17 08:14:50  brouard
                    506:   Summary: Probably last 0.98 stable version 0.98r6
                    507: 
1.222     brouard   508:   Revision 1.221  2016/02/15 23:35:36  brouard
                    509:   Summary: minor bug
                    510: 
1.220     brouard   511:   Revision 1.219  2016/02/15 00:48:12  brouard
                    512:   *** empty log message ***
                    513: 
1.219     brouard   514:   Revision 1.218  2016/02/12 11:29:23  brouard
                    515:   Summary: 0.99 Back projections
                    516: 
1.218     brouard   517:   Revision 1.217  2015/12/23 17:18:31  brouard
                    518:   Summary: Experimental backcast
                    519: 
1.217     brouard   520:   Revision 1.216  2015/12/18 17:32:11  brouard
                    521:   Summary: 0.98r4 Warning and status=-2
                    522: 
                    523:   Version 0.98r4 is now:
                    524:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    525:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    526:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    527: 
1.216     brouard   528:   Revision 1.215  2015/12/16 08:52:24  brouard
                    529:   Summary: 0.98r4 working
                    530: 
1.215     brouard   531:   Revision 1.214  2015/12/16 06:57:54  brouard
                    532:   Summary: temporary not working
                    533: 
1.214     brouard   534:   Revision 1.213  2015/12/11 18:22:17  brouard
                    535:   Summary: 0.98r4
                    536: 
1.213     brouard   537:   Revision 1.212  2015/11/21 12:47:24  brouard
                    538:   Summary: minor typo
                    539: 
1.212     brouard   540:   Revision 1.211  2015/11/21 12:41:11  brouard
                    541:   Summary: 0.98r3 with some graph of projected cross-sectional
                    542: 
                    543:   Author: Nicolas Brouard
                    544: 
1.211     brouard   545:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   546:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   547:   Summary: Adding ftolpl parameter
                    548:   Author: N Brouard
                    549: 
                    550:   We had difficulties to get smoothed confidence intervals. It was due
                    551:   to the period prevalence which wasn't computed accurately. The inner
                    552:   parameter ftolpl is now an outer parameter of the .imach parameter
                    553:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    554:   computation are long.
                    555: 
1.209     brouard   556:   Revision 1.208  2015/11/17 14:31:57  brouard
                    557:   Summary: temporary
                    558: 
1.208     brouard   559:   Revision 1.207  2015/10/27 17:36:57  brouard
                    560:   *** empty log message ***
                    561: 
1.207     brouard   562:   Revision 1.206  2015/10/24 07:14:11  brouard
                    563:   *** empty log message ***
                    564: 
1.206     brouard   565:   Revision 1.205  2015/10/23 15:50:53  brouard
                    566:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    567: 
1.205     brouard   568:   Revision 1.204  2015/10/01 16:20:26  brouard
                    569:   Summary: Some new graphs of contribution to likelihood
                    570: 
1.204     brouard   571:   Revision 1.203  2015/09/30 17:45:14  brouard
                    572:   Summary: looking at better estimation of the hessian
                    573: 
                    574:   Also a better criteria for convergence to the period prevalence And
                    575:   therefore adding the number of years needed to converge. (The
                    576:   prevalence in any alive state shold sum to one
                    577: 
1.203     brouard   578:   Revision 1.202  2015/09/22 19:45:16  brouard
                    579:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    580: 
1.202     brouard   581:   Revision 1.201  2015/09/15 17:34:58  brouard
                    582:   Summary: 0.98r0
                    583: 
                    584:   - Some new graphs like suvival functions
                    585:   - Some bugs fixed like model=1+age+V2.
                    586: 
1.201     brouard   587:   Revision 1.200  2015/09/09 16:53:55  brouard
                    588:   Summary: Big bug thanks to Flavia
                    589: 
                    590:   Even model=1+age+V2. did not work anymore
                    591: 
1.200     brouard   592:   Revision 1.199  2015/09/07 14:09:23  brouard
                    593:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    594: 
1.199     brouard   595:   Revision 1.198  2015/09/03 07:14:39  brouard
                    596:   Summary: 0.98q5 Flavia
                    597: 
1.198     brouard   598:   Revision 1.197  2015/09/01 18:24:39  brouard
                    599:   *** empty log message ***
                    600: 
1.197     brouard   601:   Revision 1.196  2015/08/18 23:17:52  brouard
                    602:   Summary: 0.98q5
                    603: 
1.196     brouard   604:   Revision 1.195  2015/08/18 16:28:39  brouard
                    605:   Summary: Adding a hack for testing purpose
                    606: 
                    607:   After reading the title, ftol and model lines, if the comment line has
                    608:   a q, starting with #q, the answer at the end of the run is quit. It
                    609:   permits to run test files in batch with ctest. The former workaround was
                    610:   $ echo q | imach foo.imach
                    611: 
1.195     brouard   612:   Revision 1.194  2015/08/18 13:32:00  brouard
                    613:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    614: 
1.194     brouard   615:   Revision 1.193  2015/08/04 07:17:42  brouard
                    616:   Summary: 0.98q4
                    617: 
1.193     brouard   618:   Revision 1.192  2015/07/16 16:49:02  brouard
                    619:   Summary: Fixing some outputs
                    620: 
1.192     brouard   621:   Revision 1.191  2015/07/14 10:00:33  brouard
                    622:   Summary: Some fixes
                    623: 
1.191     brouard   624:   Revision 1.190  2015/05/05 08:51:13  brouard
                    625:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    626: 
                    627:   Fix 1+age+.
                    628: 
1.190     brouard   629:   Revision 1.189  2015/04/30 14:45:16  brouard
                    630:   Summary: 0.98q2
                    631: 
1.189     brouard   632:   Revision 1.188  2015/04/30 08:27:53  brouard
                    633:   *** empty log message ***
                    634: 
1.188     brouard   635:   Revision 1.187  2015/04/29 09:11:15  brouard
                    636:   *** empty log message ***
                    637: 
1.187     brouard   638:   Revision 1.186  2015/04/23 12:01:52  brouard
                    639:   Summary: V1*age is working now, version 0.98q1
                    640: 
                    641:   Some codes had been disabled in order to simplify and Vn*age was
                    642:   working in the optimization phase, ie, giving correct MLE parameters,
                    643:   but, as usual, outputs were not correct and program core dumped.
                    644: 
1.186     brouard   645:   Revision 1.185  2015/03/11 13:26:42  brouard
                    646:   Summary: Inclusion of compile and links command line for Intel Compiler
                    647: 
1.185     brouard   648:   Revision 1.184  2015/03/11 11:52:39  brouard
                    649:   Summary: Back from Windows 8. Intel Compiler
                    650: 
1.184     brouard   651:   Revision 1.183  2015/03/10 20:34:32  brouard
                    652:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    653: 
                    654:   We use directest instead of original Powell test; probably no
                    655:   incidence on the results, but better justifications;
                    656:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    657:   wrong results.
                    658: 
1.183     brouard   659:   Revision 1.182  2015/02/12 08:19:57  brouard
                    660:   Summary: Trying to keep directest which seems simpler and more general
                    661:   Author: Nicolas Brouard
                    662: 
1.182     brouard   663:   Revision 1.181  2015/02/11 23:22:24  brouard
                    664:   Summary: Comments on Powell added
                    665: 
                    666:   Author:
                    667: 
1.181     brouard   668:   Revision 1.180  2015/02/11 17:33:45  brouard
                    669:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    670: 
1.180     brouard   671:   Revision 1.179  2015/01/04 09:57:06  brouard
                    672:   Summary: back to OS/X
                    673: 
1.179     brouard   674:   Revision 1.178  2015/01/04 09:35:48  brouard
                    675:   *** empty log message ***
                    676: 
1.178     brouard   677:   Revision 1.177  2015/01/03 18:40:56  brouard
                    678:   Summary: Still testing ilc32 on OSX
                    679: 
1.177     brouard   680:   Revision 1.176  2015/01/03 16:45:04  brouard
                    681:   *** empty log message ***
                    682: 
1.176     brouard   683:   Revision 1.175  2015/01/03 16:33:42  brouard
                    684:   *** empty log message ***
                    685: 
1.175     brouard   686:   Revision 1.174  2015/01/03 16:15:49  brouard
                    687:   Summary: Still in cross-compilation
                    688: 
1.174     brouard   689:   Revision 1.173  2015/01/03 12:06:26  brouard
                    690:   Summary: trying to detect cross-compilation
                    691: 
1.173     brouard   692:   Revision 1.172  2014/12/27 12:07:47  brouard
                    693:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    694: 
1.172     brouard   695:   Revision 1.171  2014/12/23 13:26:59  brouard
                    696:   Summary: Back from Visual C
                    697: 
                    698:   Still problem with utsname.h on Windows
                    699: 
1.171     brouard   700:   Revision 1.170  2014/12/23 11:17:12  brouard
                    701:   Summary: Cleaning some \%% back to %%
                    702: 
                    703:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    704: 
1.170     brouard   705:   Revision 1.169  2014/12/22 23:08:31  brouard
                    706:   Summary: 0.98p
                    707: 
                    708:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    709: 
1.169     brouard   710:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   711:   Summary: update
1.169     brouard   712: 
1.168     brouard   713:   Revision 1.167  2014/12/22 13:50:56  brouard
                    714:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    715: 
                    716:   Testing on Linux 64
                    717: 
1.167     brouard   718:   Revision 1.166  2014/12/22 11:40:47  brouard
                    719:   *** empty log message ***
                    720: 
1.166     brouard   721:   Revision 1.165  2014/12/16 11:20:36  brouard
                    722:   Summary: After compiling on Visual C
                    723: 
                    724:   * imach.c (Module): Merging 1.61 to 1.162
                    725: 
1.165     brouard   726:   Revision 1.164  2014/12/16 10:52:11  brouard
                    727:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    728: 
                    729:   * imach.c (Module): Merging 1.61 to 1.162
                    730: 
1.164     brouard   731:   Revision 1.163  2014/12/16 10:30:11  brouard
                    732:   * imach.c (Module): Merging 1.61 to 1.162
                    733: 
1.163     brouard   734:   Revision 1.162  2014/09/25 11:43:39  brouard
                    735:   Summary: temporary backup 0.99!
                    736: 
1.162     brouard   737:   Revision 1.1  2014/09/16 11:06:58  brouard
                    738:   Summary: With some code (wrong) for nlopt
                    739: 
                    740:   Author:
                    741: 
                    742:   Revision 1.161  2014/09/15 20:41:41  brouard
                    743:   Summary: Problem with macro SQR on Intel compiler
                    744: 
1.161     brouard   745:   Revision 1.160  2014/09/02 09:24:05  brouard
                    746:   *** empty log message ***
                    747: 
1.160     brouard   748:   Revision 1.159  2014/09/01 10:34:10  brouard
                    749:   Summary: WIN32
                    750:   Author: Brouard
                    751: 
1.159     brouard   752:   Revision 1.158  2014/08/27 17:11:51  brouard
                    753:   *** empty log message ***
                    754: 
1.158     brouard   755:   Revision 1.157  2014/08/27 16:26:55  brouard
                    756:   Summary: Preparing windows Visual studio version
                    757:   Author: Brouard
                    758: 
                    759:   In order to compile on Visual studio, time.h is now correct and time_t
                    760:   and tm struct should be used. difftime should be used but sometimes I
                    761:   just make the differences in raw time format (time(&now).
                    762:   Trying to suppress #ifdef LINUX
                    763:   Add xdg-open for __linux in order to open default browser.
                    764: 
1.157     brouard   765:   Revision 1.156  2014/08/25 20:10:10  brouard
                    766:   *** empty log message ***
                    767: 
1.156     brouard   768:   Revision 1.155  2014/08/25 18:32:34  brouard
                    769:   Summary: New compile, minor changes
                    770:   Author: Brouard
                    771: 
1.155     brouard   772:   Revision 1.154  2014/06/20 17:32:08  brouard
                    773:   Summary: Outputs now all graphs of convergence to period prevalence
                    774: 
1.154     brouard   775:   Revision 1.153  2014/06/20 16:45:46  brouard
                    776:   Summary: If 3 live state, convergence to period prevalence on same graph
                    777:   Author: Brouard
                    778: 
1.153     brouard   779:   Revision 1.152  2014/06/18 17:54:09  brouard
                    780:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    781: 
1.152     brouard   782:   Revision 1.151  2014/06/18 16:43:30  brouard
                    783:   *** empty log message ***
                    784: 
1.151     brouard   785:   Revision 1.150  2014/06/18 16:42:35  brouard
                    786:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    787:   Author: brouard
                    788: 
1.150     brouard   789:   Revision 1.149  2014/06/18 15:51:14  brouard
                    790:   Summary: Some fixes in parameter files errors
                    791:   Author: Nicolas Brouard
                    792: 
1.149     brouard   793:   Revision 1.148  2014/06/17 17:38:48  brouard
                    794:   Summary: Nothing new
                    795:   Author: Brouard
                    796: 
                    797:   Just a new packaging for OS/X version 0.98nS
                    798: 
1.148     brouard   799:   Revision 1.147  2014/06/16 10:33:11  brouard
                    800:   *** empty log message ***
                    801: 
1.147     brouard   802:   Revision 1.146  2014/06/16 10:20:28  brouard
                    803:   Summary: Merge
                    804:   Author: Brouard
                    805: 
                    806:   Merge, before building revised version.
                    807: 
1.146     brouard   808:   Revision 1.145  2014/06/10 21:23:15  brouard
                    809:   Summary: Debugging with valgrind
                    810:   Author: Nicolas Brouard
                    811: 
                    812:   Lot of changes in order to output the results with some covariates
                    813:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    814:   improve the code.
                    815:   No more memory valgrind error but a lot has to be done in order to
                    816:   continue the work of splitting the code into subroutines.
                    817:   Also, decodemodel has been improved. Tricode is still not
                    818:   optimal. nbcode should be improved. Documentation has been added in
                    819:   the source code.
                    820: 
1.144     brouard   821:   Revision 1.143  2014/01/26 09:45:38  brouard
                    822:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    823: 
                    824:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    825:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    826: 
1.143     brouard   827:   Revision 1.142  2014/01/26 03:57:36  brouard
                    828:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    829: 
                    830:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    831: 
1.142     brouard   832:   Revision 1.141  2014/01/26 02:42:01  brouard
                    833:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    834: 
1.141     brouard   835:   Revision 1.140  2011/09/02 10:37:54  brouard
                    836:   Summary: times.h is ok with mingw32 now.
                    837: 
1.140     brouard   838:   Revision 1.139  2010/06/14 07:50:17  brouard
                    839:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    840:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    841: 
1.139     brouard   842:   Revision 1.138  2010/04/30 18:19:40  brouard
                    843:   *** empty log message ***
                    844: 
1.138     brouard   845:   Revision 1.137  2010/04/29 18:11:38  brouard
                    846:   (Module): Checking covariates for more complex models
                    847:   than V1+V2. A lot of change to be done. Unstable.
                    848: 
1.137     brouard   849:   Revision 1.136  2010/04/26 20:30:53  brouard
                    850:   (Module): merging some libgsl code. Fixing computation
                    851:   of likelione (using inter/intrapolation if mle = 0) in order to
                    852:   get same likelihood as if mle=1.
                    853:   Some cleaning of code and comments added.
                    854: 
1.136     brouard   855:   Revision 1.135  2009/10/29 15:33:14  brouard
                    856:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    857: 
1.135     brouard   858:   Revision 1.134  2009/10/29 13:18:53  brouard
                    859:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    860: 
1.134     brouard   861:   Revision 1.133  2009/07/06 10:21:25  brouard
                    862:   just nforces
                    863: 
1.133     brouard   864:   Revision 1.132  2009/07/06 08:22:05  brouard
                    865:   Many tings
                    866: 
1.132     brouard   867:   Revision 1.131  2009/06/20 16:22:47  brouard
                    868:   Some dimensions resccaled
                    869: 
1.131     brouard   870:   Revision 1.130  2009/05/26 06:44:34  brouard
                    871:   (Module): Max Covariate is now set to 20 instead of 8. A
                    872:   lot of cleaning with variables initialized to 0. Trying to make
                    873:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    874: 
1.130     brouard   875:   Revision 1.129  2007/08/31 13:49:27  lievre
                    876:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    877: 
1.129     lievre    878:   Revision 1.128  2006/06/30 13:02:05  brouard
                    879:   (Module): Clarifications on computing e.j
                    880: 
1.128     brouard   881:   Revision 1.127  2006/04/28 18:11:50  brouard
                    882:   (Module): Yes the sum of survivors was wrong since
                    883:   imach-114 because nhstepm was no more computed in the age
                    884:   loop. Now we define nhstepma in the age loop.
                    885:   (Module): In order to speed up (in case of numerous covariates) we
                    886:   compute health expectancies (without variances) in a first step
                    887:   and then all the health expectancies with variances or standard
                    888:   deviation (needs data from the Hessian matrices) which slows the
                    889:   computation.
                    890:   In the future we should be able to stop the program is only health
                    891:   expectancies and graph are needed without standard deviations.
                    892: 
1.127     brouard   893:   Revision 1.126  2006/04/28 17:23:28  brouard
                    894:   (Module): Yes the sum of survivors was wrong since
                    895:   imach-114 because nhstepm was no more computed in the age
                    896:   loop. Now we define nhstepma in the age loop.
                    897:   Version 0.98h
                    898: 
1.126     brouard   899:   Revision 1.125  2006/04/04 15:20:31  lievre
                    900:   Errors in calculation of health expectancies. Age was not initialized.
                    901:   Forecasting file added.
                    902: 
                    903:   Revision 1.124  2006/03/22 17:13:53  lievre
                    904:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    905:   The log-likelihood is printed in the log file
                    906: 
                    907:   Revision 1.123  2006/03/20 10:52:43  brouard
                    908:   * imach.c (Module): <title> changed, corresponds to .htm file
                    909:   name. <head> headers where missing.
                    910: 
                    911:   * imach.c (Module): Weights can have a decimal point as for
                    912:   English (a comma might work with a correct LC_NUMERIC environment,
                    913:   otherwise the weight is truncated).
                    914:   Modification of warning when the covariates values are not 0 or
                    915:   1.
                    916:   Version 0.98g
                    917: 
                    918:   Revision 1.122  2006/03/20 09:45:41  brouard
                    919:   (Module): Weights can have a decimal point as for
                    920:   English (a comma might work with a correct LC_NUMERIC environment,
                    921:   otherwise the weight is truncated).
                    922:   Modification of warning when the covariates values are not 0 or
                    923:   1.
                    924:   Version 0.98g
                    925: 
                    926:   Revision 1.121  2006/03/16 17:45:01  lievre
                    927:   * imach.c (Module): Comments concerning covariates added
                    928: 
                    929:   * imach.c (Module): refinements in the computation of lli if
                    930:   status=-2 in order to have more reliable computation if stepm is
                    931:   not 1 month. Version 0.98f
                    932: 
                    933:   Revision 1.120  2006/03/16 15:10:38  lievre
                    934:   (Module): refinements in the computation of lli if
                    935:   status=-2 in order to have more reliable computation if stepm is
                    936:   not 1 month. Version 0.98f
                    937: 
                    938:   Revision 1.119  2006/03/15 17:42:26  brouard
                    939:   (Module): Bug if status = -2, the loglikelihood was
                    940:   computed as likelihood omitting the logarithm. Version O.98e
                    941: 
                    942:   Revision 1.118  2006/03/14 18:20:07  brouard
                    943:   (Module): varevsij Comments added explaining the second
                    944:   table of variances if popbased=1 .
                    945:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    946:   (Module): Function pstamp added
                    947:   (Module): Version 0.98d
                    948: 
                    949:   Revision 1.117  2006/03/14 17:16:22  brouard
                    950:   (Module): varevsij Comments added explaining the second
                    951:   table of variances if popbased=1 .
                    952:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    953:   (Module): Function pstamp added
                    954:   (Module): Version 0.98d
                    955: 
                    956:   Revision 1.116  2006/03/06 10:29:27  brouard
                    957:   (Module): Variance-covariance wrong links and
                    958:   varian-covariance of ej. is needed (Saito).
                    959: 
                    960:   Revision 1.115  2006/02/27 12:17:45  brouard
                    961:   (Module): One freematrix added in mlikeli! 0.98c
                    962: 
                    963:   Revision 1.114  2006/02/26 12:57:58  brouard
                    964:   (Module): Some improvements in processing parameter
                    965:   filename with strsep.
                    966: 
                    967:   Revision 1.113  2006/02/24 14:20:24  brouard
                    968:   (Module): Memory leaks checks with valgrind and:
                    969:   datafile was not closed, some imatrix were not freed and on matrix
                    970:   allocation too.
                    971: 
                    972:   Revision 1.112  2006/01/30 09:55:26  brouard
                    973:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    974: 
                    975:   Revision 1.111  2006/01/25 20:38:18  brouard
                    976:   (Module): Lots of cleaning and bugs added (Gompertz)
                    977:   (Module): Comments can be added in data file. Missing date values
                    978:   can be a simple dot '.'.
                    979: 
                    980:   Revision 1.110  2006/01/25 00:51:50  brouard
                    981:   (Module): Lots of cleaning and bugs added (Gompertz)
                    982: 
                    983:   Revision 1.109  2006/01/24 19:37:15  brouard
                    984:   (Module): Comments (lines starting with a #) are allowed in data.
                    985: 
                    986:   Revision 1.108  2006/01/19 18:05:42  lievre
                    987:   Gnuplot problem appeared...
                    988:   To be fixed
                    989: 
                    990:   Revision 1.107  2006/01/19 16:20:37  brouard
                    991:   Test existence of gnuplot in imach path
                    992: 
                    993:   Revision 1.106  2006/01/19 13:24:36  brouard
                    994:   Some cleaning and links added in html output
                    995: 
                    996:   Revision 1.105  2006/01/05 20:23:19  lievre
                    997:   *** empty log message ***
                    998: 
                    999:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1000:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1001:   (Module): If the status is missing at the last wave but we know
                   1002:   that the person is alive, then we can code his/her status as -2
                   1003:   (instead of missing=-1 in earlier versions) and his/her
                   1004:   contributions to the likelihood is 1 - Prob of dying from last
                   1005:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1006:   the healthy state at last known wave). Version is 0.98
                   1007: 
                   1008:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1009:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1010: 
                   1011:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1012:   Add the possibility to read data file including tab characters.
                   1013: 
                   1014:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1015:   Fix on curr_time
                   1016: 
                   1017:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1018:   Add version for Mac OS X. Just define UNIX in Makefile
                   1019: 
                   1020:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1021:   *** empty log message ***
                   1022: 
                   1023:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1024:   New version 0.97 . First attempt to estimate force of mortality
                   1025:   directly from the data i.e. without the need of knowing the health
                   1026:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1027:   This is the basic analysis of mortality and should be done before any
                   1028:   other analysis, in order to test if the mortality estimated from the
                   1029:   cross-longitudinal survey is different from the mortality estimated
                   1030:   from other sources like vital statistic data.
                   1031: 
                   1032:   The same imach parameter file can be used but the option for mle should be -3.
                   1033: 
1.324     brouard  1034:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1035:   former routines in order to include the new code within the former code.
                   1036: 
                   1037:   The output is very simple: only an estimate of the intercept and of
                   1038:   the slope with 95% confident intervals.
                   1039: 
                   1040:   Current limitations:
                   1041:   A) Even if you enter covariates, i.e. with the
                   1042:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1043:   B) There is no computation of Life Expectancy nor Life Table.
                   1044: 
                   1045:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1046:   Version 0.96d. Population forecasting command line is (temporarily)
                   1047:   suppressed.
                   1048: 
                   1049:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1050:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1051:   rewritten within the same printf. Workaround: many printfs.
                   1052: 
                   1053:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1054:   * imach.c (Repository):
                   1055:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1056:   matrix (cov(a12,c31) instead of numbers.
                   1057: 
                   1058:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1059:   Just cleaning
                   1060: 
                   1061:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1062:   (Module): On windows (cygwin) function asctime_r doesn't
                   1063:   exist so I changed back to asctime which exists.
                   1064:   (Module): Version 0.96b
                   1065: 
                   1066:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1067:   (Module): On windows (cygwin) function asctime_r doesn't
                   1068:   exist so I changed back to asctime which exists.
                   1069: 
                   1070:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1071:   * imach.c (Repository): Duplicated warning errors corrected.
                   1072:   (Repository): Elapsed time after each iteration is now output. It
                   1073:   helps to forecast when convergence will be reached. Elapsed time
                   1074:   is stamped in powell.  We created a new html file for the graphs
                   1075:   concerning matrix of covariance. It has extension -cov.htm.
                   1076: 
                   1077:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1078:   (Module): Some bugs corrected for windows. Also, when
                   1079:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1080:   of the covariance matrix to be input.
                   1081: 
                   1082:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1083:   (Module): Some bugs corrected for windows. Also, when
                   1084:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1085:   of the covariance matrix to be input.
                   1086: 
                   1087:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1088:   * 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.
                   1089: 
                   1090:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1091:   Version 0.96
                   1092: 
                   1093:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1094:   (Module): Change position of html and gnuplot routines and added
                   1095:   routine fileappend.
                   1096: 
                   1097:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1098:   * imach.c (Repository): Check when date of death was earlier that
                   1099:   current date of interview. It may happen when the death was just
                   1100:   prior to the death. In this case, dh was negative and likelihood
                   1101:   was wrong (infinity). We still send an "Error" but patch by
                   1102:   assuming that the date of death was just one stepm after the
                   1103:   interview.
                   1104:   (Repository): Because some people have very long ID (first column)
                   1105:   we changed int to long in num[] and we added a new lvector for
                   1106:   memory allocation. But we also truncated to 8 characters (left
                   1107:   truncation)
                   1108:   (Repository): No more line truncation errors.
                   1109: 
                   1110:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1111:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1112:   place. It differs from routine "prevalence" which may be called
                   1113:   many times. Probs is memory consuming and must be used with
                   1114:   parcimony.
                   1115:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1116: 
                   1117:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1118:   *** empty log message ***
                   1119: 
                   1120:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1121:   Add log in  imach.c and  fullversion number is now printed.
                   1122: 
                   1123: */
                   1124: /*
                   1125:    Interpolated Markov Chain
                   1126: 
                   1127:   Short summary of the programme:
                   1128:   
1.227     brouard  1129:   This program computes Healthy Life Expectancies or State-specific
                   1130:   (if states aren't health statuses) Expectancies from
                   1131:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1132: 
                   1133:   -1- a first survey ("cross") where individuals from different ages
                   1134:   are interviewed on their health status or degree of disability (in
                   1135:   the case of a health survey which is our main interest)
                   1136: 
                   1137:   -2- at least a second wave of interviews ("longitudinal") which
                   1138:   measure each change (if any) in individual health status.  Health
                   1139:   expectancies are computed from the time spent in each health state
                   1140:   according to a model. More health states you consider, more time is
                   1141:   necessary to reach the Maximum Likelihood of the parameters involved
                   1142:   in the model.  The simplest model is the multinomial logistic model
                   1143:   where pij is the probability to be observed in state j at the second
                   1144:   wave conditional to be observed in state i at the first
                   1145:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1146:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1147:   have a more complex model than "constant and age", you should modify
                   1148:   the program where the markup *Covariates have to be included here
                   1149:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1150:   convergence.
                   1151: 
                   1152:   The advantage of this computer programme, compared to a simple
                   1153:   multinomial logistic model, is clear when the delay between waves is not
                   1154:   identical for each individual. Also, if a individual missed an
                   1155:   intermediate interview, the information is lost, but taken into
                   1156:   account using an interpolation or extrapolation.  
                   1157: 
                   1158:   hPijx is the probability to be observed in state i at age x+h
                   1159:   conditional to the observed state i at age x. The delay 'h' can be
                   1160:   split into an exact number (nh*stepm) of unobserved intermediate
                   1161:   states. This elementary transition (by month, quarter,
                   1162:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1163:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1164:   and the contribution of each individual to the likelihood is simply
                   1165:   hPijx.
                   1166: 
                   1167:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1168:   of the life expectancies. It also computes the period (stable) prevalence.
                   1169: 
                   1170: Back prevalence and projections:
1.227     brouard  1171: 
                   1172:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1173:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1174:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1175:    mobilavproj)
                   1176: 
                   1177:     Computes the back prevalence limit for any combination of
                   1178:     covariate values k at any age between ageminpar and agemaxpar and
                   1179:     returns it in **bprlim. In the loops,
                   1180: 
                   1181:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1182:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1183: 
                   1184:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1185:    Computes for any combination of covariates k and any age between bage and fage 
                   1186:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1187:                        oldm=oldms;savm=savms;
1.227     brouard  1188: 
1.267     brouard  1189:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1190:      Computes the transition matrix starting at age 'age' over
                   1191:      'nhstepm*hstepm*stepm' months (i.e. until
                   1192:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1193:      nhstepm*hstepm matrices. 
                   1194: 
                   1195:      Returns p3mat[i][j][h] after calling
                   1196:      p3mat[i][j][h]=matprod2(newm,
                   1197:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1198:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1199:      oldm);
1.226     brouard  1200: 
                   1201: Important routines
                   1202: 
                   1203: - func (or funcone), computes logit (pij) distinguishing
                   1204:   o fixed variables (single or product dummies or quantitative);
                   1205:   o varying variables by:
                   1206:    (1) wave (single, product dummies, quantitative), 
                   1207:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1208:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1209:        % varying dummy (not done) or quantitative (not done);
                   1210: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1211:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1212: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1213:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1214:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1215: 
1.226     brouard  1216: 
                   1217:   
1.324     brouard  1218:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1219:            Institut national d'études démographiques, Paris.
1.126     brouard  1220:   This software have been partly granted by Euro-REVES, a concerted action
                   1221:   from the European Union.
                   1222:   It is copyrighted identically to a GNU software product, ie programme and
                   1223:   software can be distributed freely for non commercial use. Latest version
                   1224:   can be accessed at http://euroreves.ined.fr/imach .
                   1225: 
                   1226:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1227:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1228:   
                   1229:   **********************************************************************/
                   1230: /*
                   1231:   main
                   1232:   read parameterfile
                   1233:   read datafile
                   1234:   concatwav
                   1235:   freqsummary
                   1236:   if (mle >= 1)
                   1237:     mlikeli
                   1238:   print results files
                   1239:   if mle==1 
                   1240:      computes hessian
                   1241:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1242:       begin-prev-date,...
                   1243:   open gnuplot file
                   1244:   open html file
1.145     brouard  1245:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1246:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1247:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1248:     freexexit2 possible for memory heap.
                   1249: 
                   1250:   h Pij x                         | pij_nom  ficrestpij
                   1251:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1252:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1253:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1254: 
                   1255:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1256:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1257:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1258:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1259:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1260: 
1.126     brouard  1261:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1262:   health expectancies
                   1263:   Variance-covariance of DFLE
                   1264:   prevalence()
                   1265:    movingaverage()
                   1266:   varevsij() 
                   1267:   if popbased==1 varevsij(,popbased)
                   1268:   total life expectancies
                   1269:   Variance of period (stable) prevalence
                   1270:  end
                   1271: */
                   1272: 
1.187     brouard  1273: /* #define DEBUG */
                   1274: /* #define DEBUGBRENT */
1.203     brouard  1275: /* #define DEBUGLINMIN */
                   1276: /* #define DEBUGHESS */
                   1277: #define DEBUGHESSIJ
1.224     brouard  1278: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1279: #define POWELL /* Instead of NLOPT */
1.224     brouard  1280: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1281: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1282: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1283: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1284: 
                   1285: #include <math.h>
                   1286: #include <stdio.h>
                   1287: #include <stdlib.h>
                   1288: #include <string.h>
1.226     brouard  1289: #include <ctype.h>
1.159     brouard  1290: 
                   1291: #ifdef _WIN32
                   1292: #include <io.h>
1.172     brouard  1293: #include <windows.h>
                   1294: #include <tchar.h>
1.159     brouard  1295: #else
1.126     brouard  1296: #include <unistd.h>
1.159     brouard  1297: #endif
1.126     brouard  1298: 
                   1299: #include <limits.h>
                   1300: #include <sys/types.h>
1.171     brouard  1301: 
                   1302: #if defined(__GNUC__)
                   1303: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1304: #endif
                   1305: 
1.126     brouard  1306: #include <sys/stat.h>
                   1307: #include <errno.h>
1.159     brouard  1308: /* extern int errno; */
1.126     brouard  1309: 
1.157     brouard  1310: /* #ifdef LINUX */
                   1311: /* #include <time.h> */
                   1312: /* #include "timeval.h" */
                   1313: /* #else */
                   1314: /* #include <sys/time.h> */
                   1315: /* #endif */
                   1316: 
1.126     brouard  1317: #include <time.h>
                   1318: 
1.136     brouard  1319: #ifdef GSL
                   1320: #include <gsl/gsl_errno.h>
                   1321: #include <gsl/gsl_multimin.h>
                   1322: #endif
                   1323: 
1.167     brouard  1324: 
1.162     brouard  1325: #ifdef NLOPT
                   1326: #include <nlopt.h>
                   1327: typedef struct {
                   1328:   double (* function)(double [] );
                   1329: } myfunc_data ;
                   1330: #endif
                   1331: 
1.126     brouard  1332: /* #include <libintl.h> */
                   1333: /* #define _(String) gettext (String) */
                   1334: 
1.349     brouard  1335: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1336: 
                   1337: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1338: #define GNUPLOTVERSION 5.1
                   1339: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1340: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1341: #define FILENAMELENGTH 256
1.126     brouard  1342: 
                   1343: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1344: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1345: 
1.349     brouard  1346: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1347: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1348: 
                   1349: #define NINTERVMAX 8
1.144     brouard  1350: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1351: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1352: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1353: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1354: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1355: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1356: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1357: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1358: /* #define AGESUP 130 */
1.288     brouard  1359: /* #define AGESUP 150 */
                   1360: #define AGESUP 200
1.268     brouard  1361: #define AGEINF 0
1.218     brouard  1362: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1363: #define AGEBASE 40
1.194     brouard  1364: #define AGEOVERFLOW 1.e20
1.164     brouard  1365: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1366: #ifdef _WIN32
                   1367: #define DIRSEPARATOR '\\'
                   1368: #define CHARSEPARATOR "\\"
                   1369: #define ODIRSEPARATOR '/'
                   1370: #else
1.126     brouard  1371: #define DIRSEPARATOR '/'
                   1372: #define CHARSEPARATOR "/"
                   1373: #define ODIRSEPARATOR '\\'
                   1374: #endif
                   1375: 
1.355   ! brouard  1376: /* $Id: imach.c,v 1.354 2023/05/21 05:05:17 brouard Exp $ */
1.126     brouard  1377: /* $State: Exp $ */
1.196     brouard  1378: #include "version.h"
                   1379: char version[]=__IMACH_VERSION__;
1.352     brouard  1380: 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";
1.355   ! brouard  1381: char fullversion[]="$Revision: 1.354 $ $Date: 2023/05/21 05:05:17 $"; 
1.126     brouard  1382: char strstart[80];
                   1383: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1384: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1385: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1386: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1387: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1388: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1389: 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  1390: 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  1391: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1392: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1393: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1394: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1395: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1396: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1397: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1398: 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  1399: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1400: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1401: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1402: 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 */
                   1403: 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 */
                   1404: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1405: 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  1406: int nsd=0; /**< Total number of single dummy variables (output) */
                   1407: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1408: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1409: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1410: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1411: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1412: int cptcov=0; /* Working variable */
1.334     brouard  1413: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1414: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1415: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1416: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1417: int nlstate=2; /* Number of live states */
                   1418: int ndeath=1; /* Number of dead states */
1.130     brouard  1419: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1420: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1421: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1422: int popbased=0;
                   1423: 
                   1424: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1425: int maxwav=0; /* Maxim number of waves */
                   1426: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1427: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1428: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1429:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1430: int mle=1, weightopt=0;
1.126     brouard  1431: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1432: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1433: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1434:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1435: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1436: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1437: 
1.130     brouard  1438: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1439: double **matprod2(); /* test */
1.126     brouard  1440: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1441: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1442: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1443: 
1.136     brouard  1444: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1445: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1446: FILE *ficlog, *ficrespow;
1.130     brouard  1447: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1448: double fretone; /* Only one call to likelihood */
1.130     brouard  1449: long ipmx=0; /* Number of contributions */
1.126     brouard  1450: double sw; /* Sum of weights */
                   1451: char filerespow[FILENAMELENGTH];
                   1452: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1453: FILE *ficresilk;
                   1454: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1455: FILE *ficresprobmorprev;
                   1456: FILE *fichtm, *fichtmcov; /* Html File */
                   1457: FILE *ficreseij;
                   1458: char filerese[FILENAMELENGTH];
                   1459: FILE *ficresstdeij;
                   1460: char fileresstde[FILENAMELENGTH];
                   1461: FILE *ficrescveij;
                   1462: char filerescve[FILENAMELENGTH];
                   1463: FILE  *ficresvij;
                   1464: char fileresv[FILENAMELENGTH];
1.269     brouard  1465: 
1.126     brouard  1466: char title[MAXLINE];
1.234     brouard  1467: char model[MAXLINE]; /**< The model line */
1.217     brouard  1468: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1469: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1470: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1471: char command[FILENAMELENGTH];
                   1472: int  outcmd=0;
                   1473: 
1.217     brouard  1474: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1475: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1476: char filelog[FILENAMELENGTH]; /* Log file */
                   1477: char filerest[FILENAMELENGTH];
                   1478: char fileregp[FILENAMELENGTH];
                   1479: char popfile[FILENAMELENGTH];
                   1480: 
                   1481: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1482: 
1.157     brouard  1483: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1484: /* struct timezone tzp; */
                   1485: /* extern int gettimeofday(); */
                   1486: struct tm tml, *gmtime(), *localtime();
                   1487: 
                   1488: extern time_t time();
                   1489: 
                   1490: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1491: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1492: time_t   rlast_btime; /* raw time */
1.157     brouard  1493: struct tm tm;
                   1494: 
1.126     brouard  1495: char strcurr[80], strfor[80];
                   1496: 
                   1497: char *endptr;
                   1498: long lval;
                   1499: double dval;
                   1500: 
                   1501: #define NR_END 1
                   1502: #define FREE_ARG char*
                   1503: #define FTOL 1.0e-10
                   1504: 
                   1505: #define NRANSI 
1.240     brouard  1506: #define ITMAX 200
                   1507: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1508: 
                   1509: #define TOL 2.0e-4 
                   1510: 
                   1511: #define CGOLD 0.3819660 
                   1512: #define ZEPS 1.0e-10 
                   1513: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1514: 
                   1515: #define GOLD 1.618034 
                   1516: #define GLIMIT 100.0 
                   1517: #define TINY 1.0e-20 
                   1518: 
                   1519: static double maxarg1,maxarg2;
                   1520: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1521: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1522:   
                   1523: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1524: #define rint(a) floor(a+0.5)
1.166     brouard  1525: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1526: #define mytinydouble 1.0e-16
1.166     brouard  1527: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1528: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1529: /* static double dsqrarg; */
                   1530: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1531: static double sqrarg;
                   1532: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1533: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1534: int agegomp= AGEGOMP;
                   1535: 
                   1536: int imx; 
                   1537: int stepm=1;
                   1538: /* Stepm, step in month: minimum step interpolation*/
                   1539: 
                   1540: int estepm;
                   1541: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1542: 
                   1543: int m,nb;
                   1544: long *num;
1.197     brouard  1545: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1546: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1547:                   covariate for which somebody answered excluding 
                   1548:                   undefined. Usually 2: 0 and 1. */
                   1549: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1550:                             covariate for which somebody answered including 
                   1551:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1552: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1553: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1554: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1555: 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  1556: double *ageexmed,*agecens;
                   1557: double dateintmean=0;
1.296     brouard  1558:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1559:   double anprojf, mprojf, jprojf;
1.126     brouard  1560: 
1.296     brouard  1561:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1562:   double anbackf, mbackf, jbackf;
                   1563:   double jintmean,mintmean,aintmean;  
1.126     brouard  1564: double *weight;
                   1565: int **s; /* Status */
1.141     brouard  1566: double *agedc;
1.145     brouard  1567: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1568:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1569:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1570: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1571: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1572: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1573: double  idx; 
                   1574: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1575: /* Some documentation */
                   1576:       /*   Design original data
                   1577:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1578:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1579:        *                                                             ntv=3     nqtv=1
1.330     brouard  1580:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1581:        * For time varying covariate, quanti or dummies
                   1582:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1583:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1584:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1585:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1586:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1587:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1588:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1589:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1590:        */
                   1591: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1592: /* 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
                   1593:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1594:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1595: */
1.349     brouard  1596: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1597: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1598: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1599:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1600:                                                                /* product without age, 3 for age and double product   */
                   1601: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1602:                                                                 /*(single or product without age), 2 dummy*/
                   1603:                                                                /* with age product, 3 quant with age product*/
                   1604: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1605: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1606: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1607: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1608: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1609: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1610: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1611: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1612: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1613: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1614: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1615: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1616: /* 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"*/
                   1617: /*  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}*/
1.354     brouard  1618: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1619: /* 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}*/
                   1620: /* 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  1621: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1622: /* 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  1623: /* 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  1624: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1625: /* Type                    */
                   1626: /* V         1  2  3  4  5 */
                   1627: /*           F  F  V  V  V */
                   1628: /*           D  Q  D  D  Q */
                   1629: /*                         */
                   1630: int *TvarsD;
1.330     brouard  1631: int *TnsdVar;
1.234     brouard  1632: int *TvarsDind;
                   1633: int *TvarsQ;
                   1634: int *TvarsQind;
                   1635: 
1.318     brouard  1636: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1637: int nresult=0;
1.258     brouard  1638: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1639: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1640: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1641: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1642: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1643: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1644: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1645: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1646: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1647: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1648: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1649: 
                   1650: /* 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
                   1651:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1652:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1653: */
1.234     brouard  1654: /* 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  1655: 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 */
                   1656: 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 */
                   1657: 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 */
                   1658: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1659: 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 */
                   1660: 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  1661: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1662: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1663: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1664: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1665: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1666: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1667: 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 */
                   1668: 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  1669: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1670: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1671: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1672: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1673: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1674: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1675:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1676:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1677:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1678:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1679:       /* 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  1680: int *Tvarsel; /**< Selected covariates for output */
                   1681: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1682: 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  1683: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1684: 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  1685: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1686: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1687: int *Tage;
1.227     brouard  1688: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1689: 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  1690: 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*/ 
                   1691: 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  1692: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1693: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1694: int **Tvard;
1.330     brouard  1695: int **Tvardk;
1.227     brouard  1696: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1697: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1698: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1699:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1700:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1701: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1702: double *lsurv, *lpop, *tpop;
                   1703: 
1.231     brouard  1704: #define FD 1; /* Fixed dummy covariate */
                   1705: #define FQ 2; /* Fixed quantitative covariate */
                   1706: #define FP 3; /* Fixed product covariate */
                   1707: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1708: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1709: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1710: #define VD 10; /* Varying dummy covariate */
                   1711: #define VQ 11; /* Varying quantitative covariate */
                   1712: #define VP 12; /* Varying product covariate */
                   1713: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1714: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1715: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1716: #define APFD 16; /* Age product * fixed dummy covariate */
                   1717: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1718: #define APVD 18; /* Age product * varying dummy covariate */
                   1719: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1720: 
                   1721: #define FTYPE 1; /* Fixed covariate */
                   1722: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1723: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1724: 
                   1725: struct kmodel{
                   1726:        int maintype; /* main type */
                   1727:        int subtype; /* subtype */
                   1728: };
                   1729: struct kmodel modell[NCOVMAX];
                   1730: 
1.143     brouard  1731: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1732: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1733: 
                   1734: /**************** split *************************/
                   1735: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1736: {
                   1737:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1738:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1739:   */ 
                   1740:   char *ss;                            /* pointer */
1.186     brouard  1741:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1742: 
                   1743:   l1 = strlen(path );                  /* length of path */
                   1744:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1745:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1746:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1747:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1748:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1749:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1750:     /* get current working directory */
                   1751:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1752: #ifdef WIN32
                   1753:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1754: #else
                   1755:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1756: #endif
1.126     brouard  1757:       return( GLOCK_ERROR_GETCWD );
                   1758:     }
                   1759:     /* got dirc from getcwd*/
                   1760:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1761:   } else {                             /* strip directory from path */
1.126     brouard  1762:     ss++;                              /* after this, the filename */
                   1763:     l2 = strlen( ss );                 /* length of filename */
                   1764:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1765:     strcpy( name, ss );                /* save file name */
                   1766:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1767:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1768:     printf(" DIRC2 = %s \n",dirc);
                   1769:   }
                   1770:   /* We add a separator at the end of dirc if not exists */
                   1771:   l1 = strlen( dirc );                 /* length of directory */
                   1772:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1773:     dirc[l1] =  DIRSEPARATOR;
                   1774:     dirc[l1+1] = 0; 
                   1775:     printf(" DIRC3 = %s \n",dirc);
                   1776:   }
                   1777:   ss = strrchr( name, '.' );           /* find last / */
                   1778:   if (ss >0){
                   1779:     ss++;
                   1780:     strcpy(ext,ss);                    /* save extension */
                   1781:     l1= strlen( name);
                   1782:     l2= strlen(ss)+1;
                   1783:     strncpy( finame, name, l1-l2);
                   1784:     finame[l1-l2]= 0;
                   1785:   }
                   1786: 
                   1787:   return( 0 );                         /* we're done */
                   1788: }
                   1789: 
                   1790: 
                   1791: /******************************************/
                   1792: 
                   1793: void replace_back_to_slash(char *s, char*t)
                   1794: {
                   1795:   int i;
                   1796:   int lg=0;
                   1797:   i=0;
                   1798:   lg=strlen(t);
                   1799:   for(i=0; i<= lg; i++) {
                   1800:     (s[i] = t[i]);
                   1801:     if (t[i]== '\\') s[i]='/';
                   1802:   }
                   1803: }
                   1804: 
1.132     brouard  1805: char *trimbb(char *out, char *in)
1.137     brouard  1806: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1807:   char *s;
                   1808:   s=out;
                   1809:   while (*in != '\0'){
1.137     brouard  1810:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1811:       in++;
                   1812:     }
                   1813:     *out++ = *in++;
                   1814:   }
                   1815:   *out='\0';
                   1816:   return s;
                   1817: }
                   1818: 
1.351     brouard  1819: char *trimbtab(char *out, char *in)
                   1820: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1821:   char *s;
                   1822:   s=out;
                   1823:   while (*in != '\0'){
                   1824:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1825:       in++;
                   1826:     }
                   1827:     *out++ = *in++;
                   1828:   }
                   1829:   *out='\0';
                   1830:   return s;
                   1831: }
                   1832: 
1.187     brouard  1833: /* char *substrchaine(char *out, char *in, char *chain) */
                   1834: /* { */
                   1835: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1836: /*   char *s, *t; */
                   1837: /*   t=in;s=out; */
                   1838: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1839: /*     *out++ = *in++; */
                   1840: /*   } */
                   1841: 
                   1842: /*   /\* *in matches *chain *\/ */
                   1843: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1844: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1845: /*   } */
                   1846: /*   in--; chain--; */
                   1847: /*   while ( (*in != '\0')){ */
                   1848: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1849: /*     *out++ = *in++; */
                   1850: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1851: /*   } */
                   1852: /*   *out='\0'; */
                   1853: /*   out=s; */
                   1854: /*   return out; */
                   1855: /* } */
                   1856: char *substrchaine(char *out, char *in, char *chain)
                   1857: {
                   1858:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1859:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1860: 
                   1861:   char *strloc;
                   1862: 
1.349     brouard  1863:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1864:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1865:   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  1866:   if(strloc != NULL){ 
1.349     brouard  1867:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1868:     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)*/
                   1869:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1870:   }
1.349     brouard  1871:   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  1872:   return out;
                   1873: }
                   1874: 
                   1875: 
1.145     brouard  1876: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1877: {
1.187     brouard  1878:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1879:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1880:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1881:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1882:   */
1.160     brouard  1883:   char *s, *t;
1.145     brouard  1884:   t=in;s=in;
                   1885:   while ((*in != occ) && (*in != '\0')){
                   1886:     *alocc++ = *in++;
                   1887:   }
                   1888:   if( *in == occ){
                   1889:     *(alocc)='\0';
                   1890:     s=++in;
                   1891:   }
                   1892:  
                   1893:   if (s == t) {/* occ not found */
                   1894:     *(alocc-(in-s))='\0';
                   1895:     in=s;
                   1896:   }
                   1897:   while ( *in != '\0'){
                   1898:     *blocc++ = *in++;
                   1899:   }
                   1900: 
                   1901:   *blocc='\0';
                   1902:   return t;
                   1903: }
1.137     brouard  1904: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1905: {
1.187     brouard  1906:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1907:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1908:      gives blocc="abcdef2ghi" and alocc="j".
                   1909:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1910:   */
                   1911:   char *s, *t;
                   1912:   t=in;s=in;
                   1913:   while (*in != '\0'){
                   1914:     while( *in == occ){
                   1915:       *blocc++ = *in++;
                   1916:       s=in;
                   1917:     }
                   1918:     *blocc++ = *in++;
                   1919:   }
                   1920:   if (s == t) /* occ not found */
                   1921:     *(blocc-(in-s))='\0';
                   1922:   else
                   1923:     *(blocc-(in-s)-1)='\0';
                   1924:   in=s;
                   1925:   while ( *in != '\0'){
                   1926:     *alocc++ = *in++;
                   1927:   }
                   1928: 
                   1929:   *alocc='\0';
                   1930:   return s;
                   1931: }
                   1932: 
1.126     brouard  1933: int nbocc(char *s, char occ)
                   1934: {
                   1935:   int i,j=0;
                   1936:   int lg=20;
                   1937:   i=0;
                   1938:   lg=strlen(s);
                   1939:   for(i=0; i<= lg; i++) {
1.234     brouard  1940:     if  (s[i] == occ ) j++;
1.126     brouard  1941:   }
                   1942:   return j;
                   1943: }
                   1944: 
1.349     brouard  1945: int nboccstr(char *textin, char *chain)
                   1946: {
                   1947:   /* Counts the number of occurence of "chain"  in string textin */
                   1948:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1949:   char *strloc;
                   1950:   
                   1951:   int i,j=0;
                   1952: 
                   1953:   i=0;
                   1954: 
                   1955:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1956:   for(;;) {
                   1957:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1958:     if(strloc != NULL){
                   1959:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1960:       j++;
                   1961:     }else
                   1962:       break;
                   1963:   }
                   1964:   return j;
                   1965:   
                   1966: }
1.137     brouard  1967: /* void cutv(char *u,char *v, char*t, char occ) */
                   1968: /* { */
                   1969: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1970: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1971: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1972: /*   int i,lg,j,p=0; */
                   1973: /*   i=0; */
                   1974: /*   lg=strlen(t); */
                   1975: /*   for(j=0; j<=lg-1; j++) { */
                   1976: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1977: /*   } */
1.126     brouard  1978: 
1.137     brouard  1979: /*   for(j=0; j<p; j++) { */
                   1980: /*     (u[j] = t[j]); */
                   1981: /*   } */
                   1982: /*      u[p]='\0'; */
1.126     brouard  1983: 
1.137     brouard  1984: /*    for(j=0; j<= lg; j++) { */
                   1985: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1986: /*   } */
                   1987: /* } */
1.126     brouard  1988: 
1.160     brouard  1989: #ifdef _WIN32
                   1990: char * strsep(char **pp, const char *delim)
                   1991: {
                   1992:   char *p, *q;
                   1993:          
                   1994:   if ((p = *pp) == NULL)
                   1995:     return 0;
                   1996:   if ((q = strpbrk (p, delim)) != NULL)
                   1997:   {
                   1998:     *pp = q + 1;
                   1999:     *q = '\0';
                   2000:   }
                   2001:   else
                   2002:     *pp = 0;
                   2003:   return p;
                   2004: }
                   2005: #endif
                   2006: 
1.126     brouard  2007: /********************** nrerror ********************/
                   2008: 
                   2009: void nrerror(char error_text[])
                   2010: {
                   2011:   fprintf(stderr,"ERREUR ...\n");
                   2012:   fprintf(stderr,"%s\n",error_text);
                   2013:   exit(EXIT_FAILURE);
                   2014: }
                   2015: /*********************** vector *******************/
                   2016: double *vector(int nl, int nh)
                   2017: {
                   2018:   double *v;
                   2019:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2020:   if (!v) nrerror("allocation failure in vector");
                   2021:   return v-nl+NR_END;
                   2022: }
                   2023: 
                   2024: /************************ free vector ******************/
                   2025: void free_vector(double*v, int nl, int nh)
                   2026: {
                   2027:   free((FREE_ARG)(v+nl-NR_END));
                   2028: }
                   2029: 
                   2030: /************************ivector *******************************/
                   2031: int *ivector(long nl,long nh)
                   2032: {
                   2033:   int *v;
                   2034:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2035:   if (!v) nrerror("allocation failure in ivector");
                   2036:   return v-nl+NR_END;
                   2037: }
                   2038: 
                   2039: /******************free ivector **************************/
                   2040: void free_ivector(int *v, long nl, long nh)
                   2041: {
                   2042:   free((FREE_ARG)(v+nl-NR_END));
                   2043: }
                   2044: 
                   2045: /************************lvector *******************************/
                   2046: long *lvector(long nl,long nh)
                   2047: {
                   2048:   long *v;
                   2049:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2050:   if (!v) nrerror("allocation failure in ivector");
                   2051:   return v-nl+NR_END;
                   2052: }
                   2053: 
                   2054: /******************free lvector **************************/
                   2055: void free_lvector(long *v, long nl, long nh)
                   2056: {
                   2057:   free((FREE_ARG)(v+nl-NR_END));
                   2058: }
                   2059: 
                   2060: /******************* imatrix *******************************/
                   2061: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2062:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2063: { 
                   2064:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2065:   int **m; 
                   2066:   
                   2067:   /* allocate pointers to rows */ 
                   2068:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2069:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2070:   m += NR_END; 
                   2071:   m -= nrl; 
                   2072:   
                   2073:   
                   2074:   /* allocate rows and set pointers to them */ 
                   2075:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2076:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2077:   m[nrl] += NR_END; 
                   2078:   m[nrl] -= ncl; 
                   2079:   
                   2080:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2081:   
                   2082:   /* return pointer to array of pointers to rows */ 
                   2083:   return m; 
                   2084: } 
                   2085: 
                   2086: /****************** free_imatrix *************************/
                   2087: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2088:       int **m;
                   2089:       long nch,ncl,nrh,nrl; 
                   2090:      /* free an int matrix allocated by imatrix() */ 
                   2091: { 
                   2092:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2093:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2094: } 
                   2095: 
                   2096: /******************* matrix *******************************/
                   2097: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2098: {
                   2099:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2100:   double **m;
                   2101: 
                   2102:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2103:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2104:   m += NR_END;
                   2105:   m -= nrl;
                   2106: 
                   2107:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2108:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2109:   m[nrl] += NR_END;
                   2110:   m[nrl] -= ncl;
                   2111: 
                   2112:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2113:   return m;
1.145     brouard  2114:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2115: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2116: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2117:    */
                   2118: }
                   2119: 
                   2120: /*************************free matrix ************************/
                   2121: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2122: {
                   2123:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2124:   free((FREE_ARG)(m+nrl-NR_END));
                   2125: }
                   2126: 
                   2127: /******************* ma3x *******************************/
                   2128: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2129: {
                   2130:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2131:   double ***m;
                   2132: 
                   2133:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2134:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2135:   m += NR_END;
                   2136:   m -= nrl;
                   2137: 
                   2138:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2139:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2140:   m[nrl] += NR_END;
                   2141:   m[nrl] -= ncl;
                   2142: 
                   2143:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2144: 
                   2145:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2146:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2147:   m[nrl][ncl] += NR_END;
                   2148:   m[nrl][ncl] -= nll;
                   2149:   for (j=ncl+1; j<=nch; j++) 
                   2150:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2151:   
                   2152:   for (i=nrl+1; i<=nrh; i++) {
                   2153:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2154:     for (j=ncl+1; j<=nch; j++) 
                   2155:       m[i][j]=m[i][j-1]+nlay;
                   2156:   }
                   2157:   return m; 
                   2158:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2159:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2160:   */
                   2161: }
                   2162: 
                   2163: /*************************free ma3x ************************/
                   2164: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2165: {
                   2166:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2167:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2168:   free((FREE_ARG)(m+nrl-NR_END));
                   2169: }
                   2170: 
                   2171: /*************** function subdirf ***********/
                   2172: char *subdirf(char fileres[])
                   2173: {
                   2174:   /* Caution optionfilefiname is hidden */
                   2175:   strcpy(tmpout,optionfilefiname);
                   2176:   strcat(tmpout,"/"); /* Add to the right */
                   2177:   strcat(tmpout,fileres);
                   2178:   return tmpout;
                   2179: }
                   2180: 
                   2181: /*************** function subdirf2 ***********/
                   2182: char *subdirf2(char fileres[], char *preop)
                   2183: {
1.314     brouard  2184:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2185:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2186:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2187:   /* Caution optionfilefiname is hidden */
                   2188:   strcpy(tmpout,optionfilefiname);
                   2189:   strcat(tmpout,"/");
                   2190:   strcat(tmpout,preop);
                   2191:   strcat(tmpout,fileres);
                   2192:   return tmpout;
                   2193: }
                   2194: 
                   2195: /*************** function subdirf3 ***********/
                   2196: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2197: {
                   2198:   
                   2199:   /* Caution optionfilefiname is hidden */
                   2200:   strcpy(tmpout,optionfilefiname);
                   2201:   strcat(tmpout,"/");
                   2202:   strcat(tmpout,preop);
                   2203:   strcat(tmpout,preop2);
                   2204:   strcat(tmpout,fileres);
                   2205:   return tmpout;
                   2206: }
1.213     brouard  2207:  
                   2208: /*************** function subdirfext ***********/
                   2209: char *subdirfext(char fileres[], char *preop, char *postop)
                   2210: {
                   2211:   
                   2212:   strcpy(tmpout,preop);
                   2213:   strcat(tmpout,fileres);
                   2214:   strcat(tmpout,postop);
                   2215:   return tmpout;
                   2216: }
1.126     brouard  2217: 
1.213     brouard  2218: /*************** function subdirfext3 ***********/
                   2219: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2220: {
                   2221:   
                   2222:   /* Caution optionfilefiname is hidden */
                   2223:   strcpy(tmpout,optionfilefiname);
                   2224:   strcat(tmpout,"/");
                   2225:   strcat(tmpout,preop);
                   2226:   strcat(tmpout,fileres);
                   2227:   strcat(tmpout,postop);
                   2228:   return tmpout;
                   2229: }
                   2230:  
1.162     brouard  2231: char *asc_diff_time(long time_sec, char ascdiff[])
                   2232: {
                   2233:   long sec_left, days, hours, minutes;
                   2234:   days = (time_sec) / (60*60*24);
                   2235:   sec_left = (time_sec) % (60*60*24);
                   2236:   hours = (sec_left) / (60*60) ;
                   2237:   sec_left = (sec_left) %(60*60);
                   2238:   minutes = (sec_left) /60;
                   2239:   sec_left = (sec_left) % (60);
                   2240:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2241:   return ascdiff;
                   2242: }
                   2243: 
1.126     brouard  2244: /***************** f1dim *************************/
                   2245: extern int ncom; 
                   2246: extern double *pcom,*xicom;
                   2247: extern double (*nrfunc)(double []); 
                   2248:  
                   2249: double f1dim(double x) 
                   2250: { 
                   2251:   int j; 
                   2252:   double f;
                   2253:   double *xt; 
                   2254:  
                   2255:   xt=vector(1,ncom); 
                   2256:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2257:   f=(*nrfunc)(xt); 
                   2258:   free_vector(xt,1,ncom); 
                   2259:   return f; 
                   2260: } 
                   2261: 
                   2262: /*****************brent *************************/
                   2263: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2264: {
                   2265:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2266:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2267:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2268:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2269:    * returned function value. 
                   2270:   */
1.126     brouard  2271:   int iter; 
                   2272:   double a,b,d,etemp;
1.159     brouard  2273:   double fu=0,fv,fw,fx;
1.164     brouard  2274:   double ftemp=0.;
1.126     brouard  2275:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2276:   double e=0.0; 
                   2277:  
                   2278:   a=(ax < cx ? ax : cx); 
                   2279:   b=(ax > cx ? ax : cx); 
                   2280:   x=w=v=bx; 
                   2281:   fw=fv=fx=(*f)(x); 
                   2282:   for (iter=1;iter<=ITMAX;iter++) { 
                   2283:     xm=0.5*(a+b); 
                   2284:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2285:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2286:     printf(".");fflush(stdout);
                   2287:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2288: #ifdef DEBUGBRENT
1.126     brouard  2289:     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);
                   2290:     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);
                   2291:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2292: #endif
                   2293:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2294:       *xmin=x; 
                   2295:       return fx; 
                   2296:     } 
                   2297:     ftemp=fu;
                   2298:     if (fabs(e) > tol1) { 
                   2299:       r=(x-w)*(fx-fv); 
                   2300:       q=(x-v)*(fx-fw); 
                   2301:       p=(x-v)*q-(x-w)*r; 
                   2302:       q=2.0*(q-r); 
                   2303:       if (q > 0.0) p = -p; 
                   2304:       q=fabs(q); 
                   2305:       etemp=e; 
                   2306:       e=d; 
                   2307:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2308:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2309:       else { 
1.224     brouard  2310:                                d=p/q; 
                   2311:                                u=x+d; 
                   2312:                                if (u-a < tol2 || b-u < tol2) 
                   2313:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2314:       } 
                   2315:     } else { 
                   2316:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2317:     } 
                   2318:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2319:     fu=(*f)(u); 
                   2320:     if (fu <= fx) { 
                   2321:       if (u >= x) a=x; else b=x; 
                   2322:       SHFT(v,w,x,u) 
1.183     brouard  2323:       SHFT(fv,fw,fx,fu) 
                   2324:     } else { 
                   2325:       if (u < x) a=u; else b=u; 
                   2326:       if (fu <= fw || w == x) { 
1.224     brouard  2327:                                v=w; 
                   2328:                                w=u; 
                   2329:                                fv=fw; 
                   2330:                                fw=fu; 
1.183     brouard  2331:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2332:                                v=u; 
                   2333:                                fv=fu; 
1.183     brouard  2334:       } 
                   2335:     } 
1.126     brouard  2336:   } 
                   2337:   nrerror("Too many iterations in brent"); 
                   2338:   *xmin=x; 
                   2339:   return fx; 
                   2340: } 
                   2341: 
                   2342: /****************** mnbrak ***********************/
                   2343: 
                   2344: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2345:            double (*func)(double)) 
1.183     brouard  2346: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2347: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2348: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2349: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2350:    */
1.126     brouard  2351:   double ulim,u,r,q, dum;
                   2352:   double fu; 
1.187     brouard  2353: 
                   2354:   double scale=10.;
                   2355:   int iterscale=0;
                   2356: 
                   2357:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2358:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2359: 
                   2360: 
                   2361:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2362:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2363:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2364:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2365:   /* } */
                   2366: 
1.126     brouard  2367:   if (*fb > *fa) { 
                   2368:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2369:     SHFT(dum,*fb,*fa,dum) 
                   2370:   } 
1.126     brouard  2371:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2372:   *fc=(*func)(*cx); 
1.183     brouard  2373: #ifdef DEBUG
1.224     brouard  2374:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2375:   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  2376: #endif
1.224     brouard  2377:   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  2378:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2379:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2380:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2381:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2382:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2383:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2384:       fu=(*func)(u); 
1.163     brouard  2385: #ifdef DEBUG
                   2386:       /* f(x)=A(x-u)**2+f(u) */
                   2387:       double A, fparabu; 
                   2388:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2389:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2390:       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);
                   2391:       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  2392:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2393:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2394:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2395:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2396: #endif 
1.184     brouard  2397: #ifdef MNBRAKORIGINAL
1.183     brouard  2398: #else
1.191     brouard  2399: /*       if (fu > *fc) { */
                   2400: /* #ifdef DEBUG */
                   2401: /*       printf("mnbrak4  fu > fc \n"); */
                   2402: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2403: /* #endif */
                   2404: /*     /\* 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 *\\/  *\/ */
                   2405: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2406: /*     dum=u; /\* Shifting c and u *\/ */
                   2407: /*     u = *cx; */
                   2408: /*     *cx = dum; */
                   2409: /*     dum = fu; */
                   2410: /*     fu = *fc; */
                   2411: /*     *fc =dum; */
                   2412: /*       } else { /\* end *\/ */
                   2413: /* #ifdef DEBUG */
                   2414: /*       printf("mnbrak3  fu < fc \n"); */
                   2415: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2416: /* #endif */
                   2417: /*     dum=u; /\* Shifting c and u *\/ */
                   2418: /*     u = *cx; */
                   2419: /*     *cx = dum; */
                   2420: /*     dum = fu; */
                   2421: /*     fu = *fc; */
                   2422: /*     *fc =dum; */
                   2423: /*       } */
1.224     brouard  2424: #ifdef DEBUGMNBRAK
                   2425:                 double A, fparabu; 
                   2426:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2427:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2428:      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);
                   2429:      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  2430: #endif
1.191     brouard  2431:       dum=u; /* Shifting c and u */
                   2432:       u = *cx;
                   2433:       *cx = dum;
                   2434:       dum = fu;
                   2435:       fu = *fc;
                   2436:       *fc =dum;
1.183     brouard  2437: #endif
1.162     brouard  2438:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2439: #ifdef DEBUG
1.224     brouard  2440:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2441:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2442: #endif
1.126     brouard  2443:       fu=(*func)(u); 
                   2444:       if (fu < *fc) { 
1.183     brouard  2445: #ifdef DEBUG
1.224     brouard  2446:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2447:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2448: #endif
                   2449:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2450:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2451: #ifdef DEBUG
                   2452:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2453: #endif
                   2454:       } 
1.162     brouard  2455:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2456: #ifdef DEBUG
1.224     brouard  2457:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2458:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2459: #endif
1.126     brouard  2460:       u=ulim; 
                   2461:       fu=(*func)(u); 
1.183     brouard  2462:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2463: #ifdef DEBUG
1.224     brouard  2464:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2465:       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  2466: #endif
1.126     brouard  2467:       u=(*cx)+GOLD*(*cx-*bx); 
                   2468:       fu=(*func)(u); 
1.224     brouard  2469: #ifdef DEBUG
                   2470:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2471:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2472: #endif
1.183     brouard  2473:     } /* end tests */
1.126     brouard  2474:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2475:     SHFT(*fa,*fb,*fc,fu) 
                   2476: #ifdef DEBUG
1.224     brouard  2477:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2478:       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  2479: #endif
                   2480:   } /* 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  2481: } 
                   2482: 
                   2483: /*************** linmin ************************/
1.162     brouard  2484: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2485: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2486: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2487: the value of func at the returned location p . This is actually all accomplished by calling the
                   2488: routines mnbrak and brent .*/
1.126     brouard  2489: int ncom; 
                   2490: double *pcom,*xicom;
                   2491: double (*nrfunc)(double []); 
                   2492:  
1.224     brouard  2493: #ifdef LINMINORIGINAL
1.126     brouard  2494: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2495: #else
                   2496: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2497: #endif
1.126     brouard  2498: { 
                   2499:   double brent(double ax, double bx, double cx, 
                   2500:               double (*f)(double), double tol, double *xmin); 
                   2501:   double f1dim(double x); 
                   2502:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2503:              double *fc, double (*func)(double)); 
                   2504:   int j; 
                   2505:   double xx,xmin,bx,ax; 
                   2506:   double fx,fb,fa;
1.187     brouard  2507: 
1.203     brouard  2508: #ifdef LINMINORIGINAL
                   2509: #else
                   2510:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2511: #endif
                   2512:   
1.126     brouard  2513:   ncom=n; 
                   2514:   pcom=vector(1,n); 
                   2515:   xicom=vector(1,n); 
                   2516:   nrfunc=func; 
                   2517:   for (j=1;j<=n;j++) { 
                   2518:     pcom[j]=p[j]; 
1.202     brouard  2519:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2520:   } 
1.187     brouard  2521: 
1.203     brouard  2522: #ifdef LINMINORIGINAL
                   2523:   xx=1.;
                   2524: #else
                   2525:   axs=0.0;
                   2526:   xxs=1.;
                   2527:   do{
                   2528:     xx= xxs;
                   2529: #endif
1.187     brouard  2530:     ax=0.;
                   2531:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2532:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2533:     /* 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))   */
                   2534:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2535:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2536:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2537:     /* 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  2538: #ifdef LINMINORIGINAL
                   2539: #else
                   2540:     if (fx != fx){
1.224     brouard  2541:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2542:                        printf("|");
                   2543:                        fprintf(ficlog,"|");
1.203     brouard  2544: #ifdef DEBUGLINMIN
1.224     brouard  2545:                        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  2546: #endif
                   2547:     }
1.224     brouard  2548:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2549: #endif
                   2550:   
1.191     brouard  2551: #ifdef DEBUGLINMIN
                   2552:   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  2553:   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  2554: #endif
1.224     brouard  2555: #ifdef LINMINORIGINAL
                   2556: #else
1.317     brouard  2557:   if(fb == fx){ /* Flat function in the direction */
                   2558:     xmin=xx;
1.224     brouard  2559:     *flat=1;
1.317     brouard  2560:   }else{
1.224     brouard  2561:     *flat=0;
                   2562: #endif
                   2563:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2564:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2565:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2566:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2567:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2568:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2569: #ifdef DEBUG
1.224     brouard  2570:   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);
                   2571:   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);
                   2572: #endif
                   2573: #ifdef LINMINORIGINAL
                   2574: #else
                   2575:                        }
1.126     brouard  2576: #endif
1.191     brouard  2577: #ifdef DEBUGLINMIN
                   2578:   printf("linmin end ");
1.202     brouard  2579:   fprintf(ficlog,"linmin end ");
1.191     brouard  2580: #endif
1.126     brouard  2581:   for (j=1;j<=n;j++) { 
1.203     brouard  2582: #ifdef LINMINORIGINAL
                   2583:     xi[j] *= xmin; 
                   2584: #else
                   2585: #ifdef DEBUGLINMIN
                   2586:     if(xxs <1.0)
                   2587:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2588: #endif
                   2589:     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) */
                   2590: #ifdef DEBUGLINMIN
                   2591:     if(xxs <1.0)
                   2592:       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 );
                   2593: #endif
                   2594: #endif
1.187     brouard  2595:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2596:   } 
1.191     brouard  2597: #ifdef DEBUGLINMIN
1.203     brouard  2598:   printf("\n");
1.191     brouard  2599:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2600:   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  2601:   for (j=1;j<=n;j++) { 
1.202     brouard  2602:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2603:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2604:     if(j % ncovmodel == 0){
1.191     brouard  2605:       printf("\n");
1.202     brouard  2606:       fprintf(ficlog,"\n");
                   2607:     }
1.191     brouard  2608:   }
1.203     brouard  2609: #else
1.191     brouard  2610: #endif
1.126     brouard  2611:   free_vector(xicom,1,n); 
                   2612:   free_vector(pcom,1,n); 
                   2613: } 
                   2614: 
                   2615: 
                   2616: /*************** powell ************************/
1.162     brouard  2617: /*
1.317     brouard  2618: Minimization of a function func of n variables. Input consists in an initial starting point
                   2619: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2620: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2621: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2622: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2623: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2624:  */
1.224     brouard  2625: #ifdef LINMINORIGINAL
                   2626: #else
                   2627:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2628:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2629: #endif
1.126     brouard  2630: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2631:            double (*func)(double [])) 
                   2632: { 
1.224     brouard  2633: #ifdef LINMINORIGINAL
                   2634:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2635:              double (*func)(double [])); 
1.224     brouard  2636: #else 
1.241     brouard  2637:  void linmin(double p[], double xi[], int n, double *fret,
                   2638:             double (*func)(double []),int *flat); 
1.224     brouard  2639: #endif
1.239     brouard  2640:  int i,ibig,j,jk,k; 
1.126     brouard  2641:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2642:   double directest;
1.126     brouard  2643:   double fp,fptt;
                   2644:   double *xits;
                   2645:   int niterf, itmp;
1.349     brouard  2646:   int Bigter=0, nBigterf=1;
                   2647:   
1.126     brouard  2648:   pt=vector(1,n); 
                   2649:   ptt=vector(1,n); 
                   2650:   xit=vector(1,n); 
                   2651:   xits=vector(1,n); 
                   2652:   *fret=(*func)(p); 
                   2653:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2654:   rcurr_time = time(NULL);
                   2655:   fp=(*fret); /* Initialisation */
1.126     brouard  2656:   for (*iter=1;;++(*iter)) { 
                   2657:     ibig=0; 
                   2658:     del=0.0; 
1.157     brouard  2659:     rlast_time=rcurr_time;
1.349     brouard  2660:     rlast_btime=rcurr_time;
1.157     brouard  2661:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2662:     rcurr_time = time(NULL);  
                   2663:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2664:     /* 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); */
                   2665:     /* 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  2666:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2667:     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);
                   2668:     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);
                   2669:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2670:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2671:     for (i=1;i<=n;i++) {
1.126     brouard  2672:       fprintf(ficrespow," %.12lf", p[i]);
                   2673:     }
1.239     brouard  2674:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2675:     printf("\n#model=  1      +     age ");
                   2676:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2677:     if(nagesqr==1){
1.241     brouard  2678:        printf("  + age*age  ");
                   2679:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2680:     }
                   2681:     for(j=1;j <=ncovmodel-2;j++){
                   2682:       if(Typevar[j]==0) {
                   2683:        printf("  +      V%d  ",Tvar[j]);
                   2684:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2685:       }else if(Typevar[j]==1) {
                   2686:        printf("  +    V%d*age ",Tvar[j]);
                   2687:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2688:       }else if(Typevar[j]==2) {
                   2689:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2690:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2691:       }else if(Typevar[j]==3) {
                   2692:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2693:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2694:       }
                   2695:     }
1.126     brouard  2696:     printf("\n");
1.239     brouard  2697: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2698: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2699:     fprintf(ficlog,"\n");
1.239     brouard  2700:     for(i=1,jk=1; i <=nlstate; i++){
                   2701:       for(k=1; k <=(nlstate+ndeath); k++){
                   2702:        if (k != i) {
                   2703:          printf("%d%d ",i,k);
                   2704:          fprintf(ficlog,"%d%d ",i,k);
                   2705:          for(j=1; j <=ncovmodel; j++){
                   2706:            printf("%12.7f ",p[jk]);
                   2707:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2708:            jk++; 
                   2709:          }
                   2710:          printf("\n");
                   2711:          fprintf(ficlog,"\n");
                   2712:        }
                   2713:       }
                   2714:     }
1.241     brouard  2715:     if(*iter <=3 && *iter >1){
1.157     brouard  2716:       tml = *localtime(&rcurr_time);
                   2717:       strcpy(strcurr,asctime(&tml));
                   2718:       rforecast_time=rcurr_time; 
1.126     brouard  2719:       itmp = strlen(strcurr);
                   2720:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2721:        strcurr[itmp-1]='\0';
1.162     brouard  2722:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2723:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2724:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2725:        niterf=nBigterf*ncovmodel;
                   2726:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2727:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2728:        forecast_time = *localtime(&rforecast_time);
                   2729:        strcpy(strfor,asctime(&forecast_time));
                   2730:        itmp = strlen(strfor);
                   2731:        if(strfor[itmp-1]=='\n')
                   2732:          strfor[itmp-1]='\0';
1.349     brouard  2733:        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);
                   2734:        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  2735:       }
                   2736:     }
1.187     brouard  2737:     for (i=1;i<=n;i++) { /* For each direction i */
                   2738:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2739:       fptt=(*fret); 
                   2740: #ifdef DEBUG
1.203     brouard  2741:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2742:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2743: #endif
1.203     brouard  2744:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2745:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2746: #ifdef LINMINORIGINAL
1.188     brouard  2747:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2748: #else
                   2749:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2750:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2751: #endif
                   2752:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2753:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2754:                                /* because that direction will be replaced unless the gain del is small */
                   2755:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2756:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2757:                                /* with the new direction. */
                   2758:                                del=fabs(fptt-(*fret)); 
                   2759:                                ibig=i; 
1.126     brouard  2760:       } 
                   2761: #ifdef DEBUG
                   2762:       printf("%d %.12e",i,(*fret));
                   2763:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2764:       for (j=1;j<=n;j++) {
1.224     brouard  2765:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2766:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2767:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2768:       }
                   2769:       for(j=1;j<=n;j++) {
1.225     brouard  2770:                                printf(" p(%d)=%.12e",j,p[j]);
                   2771:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2772:       }
                   2773:       printf("\n");
                   2774:       fprintf(ficlog,"\n");
                   2775: #endif
1.187     brouard  2776:     } /* end loop on each direction i */
                   2777:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2778:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2779:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2780:     for(j=1;j<=n;j++) {
                   2781:       if(flatdir[j] >0){
                   2782:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2783:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2784:       }
1.319     brouard  2785:       /* printf("\n"); */
                   2786:       /* fprintf(ficlog,"\n"); */
                   2787:     }
1.243     brouard  2788:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2789:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2790:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2791:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2792:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2793:       /* decreased of more than 3.84  */
                   2794:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2795:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2796:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2797:                        
1.188     brouard  2798:       /* Starting the program with initial values given by a former maximization will simply change */
                   2799:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2800:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2801:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2802: #ifdef DEBUG
                   2803:       int k[2],l;
                   2804:       k[0]=1;
                   2805:       k[1]=-1;
                   2806:       printf("Max: %.12e",(*func)(p));
                   2807:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2808:       for (j=1;j<=n;j++) {
                   2809:        printf(" %.12e",p[j]);
                   2810:        fprintf(ficlog," %.12e",p[j]);
                   2811:       }
                   2812:       printf("\n");
                   2813:       fprintf(ficlog,"\n");
                   2814:       for(l=0;l<=1;l++) {
                   2815:        for (j=1;j<=n;j++) {
                   2816:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2817:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2818:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2819:        }
                   2820:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2821:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2822:       }
                   2823: #endif
                   2824: 
                   2825:       free_vector(xit,1,n); 
                   2826:       free_vector(xits,1,n); 
                   2827:       free_vector(ptt,1,n); 
                   2828:       free_vector(pt,1,n); 
                   2829:       return; 
1.192     brouard  2830:     } /* enough precision */ 
1.240     brouard  2831:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2832:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2833:       ptt[j]=2.0*p[j]-pt[j]; 
                   2834:       xit[j]=p[j]-pt[j]; 
                   2835:       pt[j]=p[j]; 
                   2836:     } 
1.181     brouard  2837:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2838: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2839:                if (*iter <=4) {
1.225     brouard  2840: #else
                   2841: #endif
1.224     brouard  2842: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2843: #else
1.161     brouard  2844:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2845: #endif
1.162     brouard  2846:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2847:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2848:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2849:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2850:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2851:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2852:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2853:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2854:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2855:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2856:       /* mu² and del² are equal when f3=f1 */
                   2857:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2858:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2859:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2860:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2861: #ifdef NRCORIGINAL
                   2862:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2863: #else
                   2864:       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  2865:       t= t- del*SQR(fp-fptt);
1.183     brouard  2866: #endif
1.202     brouard  2867:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2868: #ifdef DEBUG
1.181     brouard  2869:       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);
                   2870:       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  2871:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2872:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2873:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2874:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2875:       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);
                   2876:       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);
                   2877: #endif
1.183     brouard  2878: #ifdef POWELLORIGINAL
                   2879:       if (t < 0.0) { /* Then we use it for new direction */
                   2880: #else
1.182     brouard  2881:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2882:                                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  2883:         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  2884:         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  2885:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2886:       } 
1.181     brouard  2887:       if (directest < 0.0) { /* Then we use it for new direction */
                   2888: #endif
1.191     brouard  2889: #ifdef DEBUGLINMIN
1.234     brouard  2890:        printf("Before linmin in direction P%d-P0\n",n);
                   2891:        for (j=1;j<=n;j++) {
                   2892:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2893:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2894:          if(j % ncovmodel == 0){
                   2895:            printf("\n");
                   2896:            fprintf(ficlog,"\n");
                   2897:          }
                   2898:        }
1.224     brouard  2899: #endif
                   2900: #ifdef LINMINORIGINAL
1.234     brouard  2901:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2902: #else
1.234     brouard  2903:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2904:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2905: #endif
1.234     brouard  2906:        
1.191     brouard  2907: #ifdef DEBUGLINMIN
1.234     brouard  2908:        for (j=1;j<=n;j++) { 
                   2909:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2910:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2911:          if(j % ncovmodel == 0){
                   2912:            printf("\n");
                   2913:            fprintf(ficlog,"\n");
                   2914:          }
                   2915:        }
1.224     brouard  2916: #endif
1.234     brouard  2917:        for (j=1;j<=n;j++) { 
                   2918:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2919:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2920:        }
1.224     brouard  2921: #ifdef LINMINORIGINAL
                   2922: #else
1.234     brouard  2923:        for (j=1, flatd=0;j<=n;j++) {
                   2924:          if(flatdir[j]>0)
                   2925:            flatd++;
                   2926:        }
                   2927:        if(flatd >0){
1.255     brouard  2928:          printf("%d flat directions: ",flatd);
                   2929:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2930:          for (j=1;j<=n;j++) { 
                   2931:            if(flatdir[j]>0){
                   2932:              printf("%d ",j);
                   2933:              fprintf(ficlog,"%d ",j);
                   2934:            }
                   2935:          }
                   2936:          printf("\n");
                   2937:          fprintf(ficlog,"\n");
1.319     brouard  2938: #ifdef FLATSUP
                   2939:           free_vector(xit,1,n); 
                   2940:           free_vector(xits,1,n); 
                   2941:           free_vector(ptt,1,n); 
                   2942:           free_vector(pt,1,n); 
                   2943:           return;
                   2944: #endif
1.234     brouard  2945:        }
1.191     brouard  2946: #endif
1.234     brouard  2947:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2948:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2949:        
1.126     brouard  2950: #ifdef DEBUG
1.234     brouard  2951:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2952:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2953:        for(j=1;j<=n;j++){
                   2954:          printf(" %lf",xit[j]);
                   2955:          fprintf(ficlog," %lf",xit[j]);
                   2956:        }
                   2957:        printf("\n");
                   2958:        fprintf(ficlog,"\n");
1.126     brouard  2959: #endif
1.192     brouard  2960:       } /* end of t or directest negative */
1.224     brouard  2961: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2962: #else
1.234     brouard  2963:       } /* end if (fptt < fp)  */
1.192     brouard  2964: #endif
1.225     brouard  2965: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2966:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2967: #else
1.224     brouard  2968: #endif
1.234     brouard  2969:                } /* loop iteration */ 
1.126     brouard  2970: } 
1.234     brouard  2971:   
1.126     brouard  2972: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2973:   
1.235     brouard  2974:   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  2975:   {
1.338     brouard  2976:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2977:      *   (and selected quantitative values in nres)
                   2978:      *  by left multiplying the unit
                   2979:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2980:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2981:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2982:      * or prevalence in state 1, prevalence in state 2, 0
                   2983:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2984:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2985:      * Output is prlim.
                   2986:      * Initial matrix pimij 
                   2987:      */
1.206     brouard  2988:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2989:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2990:   /*  0,                   0                  , 1} */
                   2991:   /*
                   2992:    * and after some iteration: */
                   2993:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2994:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2995:   /*  0,                   0                  , 1} */
                   2996:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2997:   /* {0.51571254859325999, 0.4842874514067399, */
                   2998:   /*  0.51326036147820708, 0.48673963852179264} */
                   2999:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  3000:     
1.332     brouard  3001:     int i, ii,j,k, k1;
1.209     brouard  3002:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  3003:   /* double **matprod2(); */ /* test */
1.218     brouard  3004:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  3005:   double **newm;
1.209     brouard  3006:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  3007:   int ncvloop=0;
1.288     brouard  3008:   int first=0;
1.169     brouard  3009:   
1.209     brouard  3010:   min=vector(1,nlstate);
                   3011:   max=vector(1,nlstate);
                   3012:   meandiff=vector(1,nlstate);
                   3013: 
1.218     brouard  3014:        /* Starting with matrix unity */
1.126     brouard  3015:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3016:     for (j=1;j<=nlstate+ndeath;j++){
                   3017:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3018:     }
1.169     brouard  3019:   
                   3020:   cov[1]=1.;
                   3021:   
                   3022:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  3023:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  3024:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  3025:     ncvloop++;
1.126     brouard  3026:     newm=savm;
                   3027:     /* Covariates have to be included here again */
1.138     brouard  3028:     cov[2]=agefin;
1.319     brouard  3029:      if(nagesqr==1){
                   3030:       cov[3]= agefin*agefin;
                   3031:      }
1.332     brouard  3032:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3033:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3034:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3035:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3036:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3037:        }else{
                   3038:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3039:        }
                   3040:      }/* End of loop on model equation */
                   3041:      
                   3042: /* Start of old code (replaced by a loop on position in the model equation */
                   3043:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3044:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3045:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3046:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3047:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3048:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3049:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3050:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3051:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3052:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3053:     /*    *nsd=3                              (1)  (2)           (3) */
                   3054:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3055:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3056:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3057:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3058:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3059:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3060:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3061:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3062:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3063:     /*    *TvarsDpType */
                   3064:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3065:     /*    * nsd=1              (1)           (2) */
                   3066:     /*    *TvarsD[nsd]          3             2 */
                   3067:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3068:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3069:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3070:     /*    *\/ */
                   3071:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3072:     /*   /\* 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)); *\/ */
                   3073:     /* } */
                   3074:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3075:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3076:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3077:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3078:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3079:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3080:     /*   /\* 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]); *\/ */
                   3081:     /* } */
                   3082:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3083:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3084:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3085:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3086:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3087:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3088:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3089:     /*   } */
                   3090:     /*   /\* 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]); *\/ */
                   3091:     /* } */
                   3092:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3093:     /*   /\* 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]); *\/ */
                   3094:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3095:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3096:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3097:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3098:     /*         }else{ */
                   3099:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3100:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3101:     /*         } */
                   3102:     /*   }else{ */
                   3103:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3104:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3105:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3106:     /*         }else{ */
                   3107:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3108:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3109:     /*         } */
                   3110:     /*   } */
                   3111:     /* } /\* End product without age *\/ */
                   3112: /* ENd of old code */
1.138     brouard  3113:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3114:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3115:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3116:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3117:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3118:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3119:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3120:     
1.126     brouard  3121:     savm=oldm;
                   3122:     oldm=newm;
1.209     brouard  3123: 
                   3124:     for(j=1; j<=nlstate; j++){
                   3125:       max[j]=0.;
                   3126:       min[j]=1.;
                   3127:     }
                   3128:     for(i=1;i<=nlstate;i++){
                   3129:       sumnew=0;
                   3130:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3131:       for(j=1; j<=nlstate; j++){ 
                   3132:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3133:        max[j]=FMAX(max[j],prlim[i][j]);
                   3134:        min[j]=FMIN(min[j],prlim[i][j]);
                   3135:       }
                   3136:     }
                   3137: 
1.126     brouard  3138:     maxmax=0.;
1.209     brouard  3139:     for(j=1; j<=nlstate; j++){
                   3140:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3141:       maxmax=FMAX(maxmax,meandiff[j]);
                   3142:       /* 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  3143:     } /* j loop */
1.203     brouard  3144:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3145:     /* 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  3146:     if(maxmax < ftolpl){
1.209     brouard  3147:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3148:       free_vector(min,1,nlstate);
                   3149:       free_vector(max,1,nlstate);
                   3150:       free_vector(meandiff,1,nlstate);
1.126     brouard  3151:       return prlim;
                   3152:     }
1.288     brouard  3153:   } /* agefin loop */
1.208     brouard  3154:     /* After some age loop it doesn't converge */
1.288     brouard  3155:   if(!first){
                   3156:     first=1;
                   3157:     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  3158:     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);
                   3159:   }else if (first >=1 && first <10){
                   3160:     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);
                   3161:     first++;
                   3162:   }else if (first ==10){
                   3163:     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);
                   3164:     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");
                   3165:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3166:     first++;
1.288     brouard  3167:   }
                   3168: 
1.209     brouard  3169:   /* 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); */
                   3170:   free_vector(min,1,nlstate);
                   3171:   free_vector(max,1,nlstate);
                   3172:   free_vector(meandiff,1,nlstate);
1.208     brouard  3173:   
1.169     brouard  3174:   return prlim; /* should not reach here */
1.126     brouard  3175: }
                   3176: 
1.217     brouard  3177: 
                   3178:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3179: 
1.218     brouard  3180:  /* 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) */
                   3181:  /* 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  3182:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3183: {
1.264     brouard  3184:   /* 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  3185:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3186:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3187:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3188:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3189:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3190:   /* Initial matrix pimij */
                   3191:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3192:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3193:   /*  0,                   0                  , 1} */
                   3194:   /*
                   3195:    * and after some iteration: */
                   3196:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3197:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3198:   /*  0,                   0                  , 1} */
                   3199:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3200:   /* {0.51571254859325999, 0.4842874514067399, */
                   3201:   /*  0.51326036147820708, 0.48673963852179264} */
                   3202:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3203: 
1.332     brouard  3204:   int i, ii,j,k, k1;
1.247     brouard  3205:   int first=0;
1.217     brouard  3206:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3207:   /* double **matprod2(); */ /* test */
                   3208:   double **out, cov[NCOVMAX+1], **bmij();
                   3209:   double **newm;
1.218     brouard  3210:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3211:   double        **oldm, **savm;  /* for use */
                   3212: 
1.217     brouard  3213:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3214:   int ncvloop=0;
                   3215:   
                   3216:   min=vector(1,nlstate);
                   3217:   max=vector(1,nlstate);
                   3218:   meandiff=vector(1,nlstate);
                   3219: 
1.266     brouard  3220:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3221:   oldm=oldms; savm=savms;
                   3222:   
                   3223:   /* Starting with matrix unity */
                   3224:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3225:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3226:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3227:     }
                   3228:   
                   3229:   cov[1]=1.;
                   3230:   
                   3231:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3232:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3233:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3234:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3235:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3236:     ncvloop++;
1.218     brouard  3237:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3238:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3239:     /* Covariates have to be included here again */
                   3240:     cov[2]=agefin;
1.319     brouard  3241:     if(nagesqr==1){
1.217     brouard  3242:       cov[3]= agefin*agefin;;
1.319     brouard  3243:     }
1.332     brouard  3244:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3245:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3246:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3247:       }else{
1.332     brouard  3248:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3249:       }
1.332     brouard  3250:     }/* End of loop on model equation */
                   3251: 
                   3252: /* Old code */ 
                   3253: 
                   3254:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3255:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3256:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3257:     /*   /\* 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)); *\/ */
                   3258:     /* } */
                   3259:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3260:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3261:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3262:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3263:     /* /\* } *\/ */
                   3264:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3265:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3266:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3267:     /*   /\* 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]); *\/ */
                   3268:     /* } */
                   3269:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3270:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3271:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3272:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3273:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3274:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3275:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3276:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3277:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3278:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3279:     /*   } */
                   3280:     /*   /\* 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]); *\/ */
                   3281:     /* } */
                   3282:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3283:     /*   /\* 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]); *\/ */
                   3284:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3285:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3286:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3287:     /*         }else{ */
                   3288:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3289:     /*         } */
                   3290:     /*   }else{ */
                   3291:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3292:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3293:     /*         }else{ */
                   3294:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3295:     /*         } */
                   3296:     /*   } */
                   3297:     /* } */
1.217     brouard  3298:     
                   3299:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3300:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3301:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3302:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3303:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3304:                /* ij should be linked to the correct index of cov */
                   3305:                /* age and covariate values ij are in 'cov', but we need to pass
                   3306:                 * ij for the observed prevalence at age and status and covariate
                   3307:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3308:                 */
                   3309:     /* 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 *\/ */
                   3310:     /* 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 *\/ */
                   3311:     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  3312:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3313:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3314:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3315:     /*         printf("%d newm= ",i); */
                   3316:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3317:     /*           printf("%f ",newm[i][j]); */
                   3318:     /*         } */
                   3319:     /*         printf("oldm * "); */
                   3320:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3321:     /*           printf("%f ",oldm[i][j]); */
                   3322:     /*         } */
1.268     brouard  3323:     /*         printf(" bmmij "); */
1.266     brouard  3324:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3325:     /*           printf("%f ",pmmij[i][j]); */
                   3326:     /*         } */
                   3327:     /*         printf("\n"); */
                   3328:     /*   } */
                   3329:     /* } */
1.217     brouard  3330:     savm=oldm;
                   3331:     oldm=newm;
1.266     brouard  3332: 
1.217     brouard  3333:     for(j=1; j<=nlstate; j++){
                   3334:       max[j]=0.;
                   3335:       min[j]=1.;
                   3336:     }
                   3337:     for(j=1; j<=nlstate; j++){ 
                   3338:       for(i=1;i<=nlstate;i++){
1.234     brouard  3339:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3340:        bprlim[i][j]= newm[i][j];
                   3341:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3342:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3343:       }
                   3344:     }
1.218     brouard  3345:                
1.217     brouard  3346:     maxmax=0.;
                   3347:     for(i=1; i<=nlstate; i++){
1.318     brouard  3348:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3349:       maxmax=FMAX(maxmax,meandiff[i]);
                   3350:       /* 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  3351:     } /* i loop */
1.217     brouard  3352:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3353:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3354:     if(maxmax < ftolpl){
1.220     brouard  3355:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3356:       free_vector(min,1,nlstate);
                   3357:       free_vector(max,1,nlstate);
                   3358:       free_vector(meandiff,1,nlstate);
                   3359:       return bprlim;
                   3360:     }
1.288     brouard  3361:   } /* agefin loop */
1.217     brouard  3362:     /* After some age loop it doesn't converge */
1.288     brouard  3363:   if(!first){
1.247     brouard  3364:     first=1;
                   3365:     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\
                   3366: 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);
                   3367:   }
                   3368:   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  3369: 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);
                   3370:   /* 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); */
                   3371:   free_vector(min,1,nlstate);
                   3372:   free_vector(max,1,nlstate);
                   3373:   free_vector(meandiff,1,nlstate);
                   3374:   
                   3375:   return bprlim; /* should not reach here */
                   3376: }
                   3377: 
1.126     brouard  3378: /*************** transition probabilities ***************/ 
                   3379: 
                   3380: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3381: {
1.138     brouard  3382:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3383:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3384:      model to the ncovmodel covariates (including constant and age).
                   3385:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3386:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3387:      ncth covariate in the global vector x is given by the formula:
                   3388:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3389:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3390:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3391:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3392:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3393:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3394:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3395:   */
                   3396:   double s1, lnpijopii;
1.126     brouard  3397:   /*double t34;*/
1.164     brouard  3398:   int i,j, nc, ii, jj;
1.126     brouard  3399: 
1.223     brouard  3400:   for(i=1; i<= nlstate; i++){
                   3401:     for(j=1; j<i;j++){
                   3402:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3403:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3404:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3405:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",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:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3411:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3412:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3413:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3414:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3415:       }
                   3416:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3417:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3418:     }
                   3419:   }
1.218     brouard  3420:   
1.223     brouard  3421:   for(i=1; i<= nlstate; i++){
                   3422:     s1=0;
                   3423:     for(j=1; j<i; j++){
1.339     brouard  3424:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3425:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3426:     }
                   3427:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3428:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3429:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3430:     }
                   3431:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3432:     ps[i][i]=1./(s1+1.);
                   3433:     /* Computing other pijs */
                   3434:     for(j=1; j<i; j++)
1.325     brouard  3435:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3436:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3437:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3438:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3439:   } /* end i */
1.218     brouard  3440:   
1.223     brouard  3441:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3442:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3443:       ps[ii][jj]=0;
                   3444:       ps[ii][ii]=1;
                   3445:     }
                   3446:   }
1.294     brouard  3447: 
                   3448: 
1.223     brouard  3449:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3450:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3451:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3452:   /*   } */
                   3453:   /*   printf("\n "); */
                   3454:   /* } */
                   3455:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3456:   /*
                   3457:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3458:                goto end;*/
1.266     brouard  3459:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3460: }
                   3461: 
1.218     brouard  3462: /*************** backward transition probabilities ***************/ 
                   3463: 
                   3464:  /* 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 ) */
                   3465: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3466:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3467: {
1.302     brouard  3468:   /* 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  3469:    * 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  3470:    */
1.218     brouard  3471:   int i, ii, j,k;
1.222     brouard  3472:   
                   3473:   double **out, **pmij();
                   3474:   double sumnew=0.;
1.218     brouard  3475:   double agefin;
1.292     brouard  3476:   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  3477:   double **dnewm, **dsavm, **doldm;
                   3478:   double **bbmij;
                   3479:   
1.218     brouard  3480:   doldm=ddoldms; /* global pointers */
1.222     brouard  3481:   dnewm=ddnewms;
                   3482:   dsavm=ddsavms;
1.318     brouard  3483: 
                   3484:   /* Debug */
                   3485:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3486:   agefin=cov[2];
1.268     brouard  3487:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3488:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3489:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3490:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3491: 
                   3492:   /* P_x */
1.325     brouard  3493:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3494:   /* outputs pmmij which is a stochastic matrix in row */
                   3495: 
                   3496:   /* Diag(w_x) */
1.292     brouard  3497:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3498:   sumnew=0.;
1.269     brouard  3499:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3500:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3501:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3502:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3503:   }
                   3504:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3505:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3506:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3507:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3508:     }
                   3509:   }else{
                   3510:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3511:       for (j=1;j<=nlstate+ndeath;j++)
                   3512:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3513:     }
                   3514:     /* if(sumnew <0.9){ */
                   3515:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3516:     /* } */
                   3517:   }
                   3518:   k3=0.0;  /* We put the last diagonal to 0 */
                   3519:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3520:       doldm[ii][ii]= k3;
                   3521:   }
                   3522:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3523:   
1.292     brouard  3524:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3525:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3526: 
1.292     brouard  3527:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3528:   /* 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  3529:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3530:     sumnew=0.;
1.222     brouard  3531:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3532:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3533:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3534:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3535:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3536:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3537:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3538:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3539:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3540:        /* }else */
1.268     brouard  3541:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3542:     } /*End ii */
                   3543:   } /* 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 */
                   3544: 
1.292     brouard  3545:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3546:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3547:   /* end bmij */
1.266     brouard  3548:   return ps; /*pointer is unchanged */
1.218     brouard  3549: }
1.217     brouard  3550: /*************** transition probabilities ***************/ 
                   3551: 
1.218     brouard  3552: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3553: {
                   3554:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3555:      computes the probability to be observed in state j being in state i by appying the
                   3556:      model to the ncovmodel covariates (including constant and age).
                   3557:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3558:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3559:      ncth covariate in the global vector x is given by the formula:
                   3560:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3561:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3562:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3563:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3564:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3565:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3566:   */
                   3567:   double s1, lnpijopii;
                   3568:   /*double t34;*/
                   3569:   int i,j, nc, ii, jj;
                   3570: 
1.234     brouard  3571:   for(i=1; i<= nlstate; i++){
                   3572:     for(j=1; j<i;j++){
                   3573:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3574:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3575:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3576:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3577:       }
                   3578:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3579:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3580:     }
                   3581:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3582:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3583:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3584:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3585:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3586:       }
                   3587:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3588:     }
                   3589:   }
                   3590:   
                   3591:   for(i=1; i<= nlstate; i++){
                   3592:     s1=0;
                   3593:     for(j=1; j<i; j++){
                   3594:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3595:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3596:     }
                   3597:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3598:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3599:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3600:     }
                   3601:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3602:     ps[i][i]=1./(s1+1.);
                   3603:     /* Computing other pijs */
                   3604:     for(j=1; j<i; j++)
                   3605:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3606:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3607:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3608:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3609:   } /* end i */
                   3610:   
                   3611:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3612:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3613:       ps[ii][jj]=0;
                   3614:       ps[ii][ii]=1;
                   3615:     }
                   3616:   }
1.296     brouard  3617:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3618:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3619:     s1=0.;
                   3620:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3621:       s1+=ps[ii][jj];
                   3622:     }
                   3623:     for(ii=1; ii<= nlstate; ii++){
                   3624:       ps[ii][jj]=ps[ii][jj]/s1;
                   3625:     }
                   3626:   }
                   3627:   /* Transposition */
                   3628:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3629:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3630:       s1=ps[ii][jj];
                   3631:       ps[ii][jj]=ps[jj][ii];
                   3632:       ps[jj][ii]=s1;
                   3633:     }
                   3634:   }
                   3635:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3636:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3637:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3638:   /*   } */
                   3639:   /*   printf("\n "); */
                   3640:   /* } */
                   3641:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3642:   /*
                   3643:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3644:     goto end;*/
                   3645:   return ps;
1.217     brouard  3646: }
                   3647: 
                   3648: 
1.126     brouard  3649: /**************** Product of 2 matrices ******************/
                   3650: 
1.145     brouard  3651: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3652: {
                   3653:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3654:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3655:   /* in, b, out are matrice of pointers which should have been initialized 
                   3656:      before: only the contents of out is modified. The function returns
                   3657:      a pointer to pointers identical to out */
1.145     brouard  3658:   int i, j, k;
1.126     brouard  3659:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3660:     for(k=ncolol; k<=ncoloh; k++){
                   3661:       out[i][k]=0.;
                   3662:       for(j=ncl; j<=nch; j++)
                   3663:        out[i][k] +=in[i][j]*b[j][k];
                   3664:     }
1.126     brouard  3665:   return out;
                   3666: }
                   3667: 
                   3668: 
                   3669: /************* Higher Matrix Product ***************/
                   3670: 
1.235     brouard  3671: 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  3672: {
1.336     brouard  3673:   /* Already optimized with precov.
                   3674:      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  3675:      'nhstepm*hstepm*stepm' months (i.e. until
                   3676:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3677:      nhstepm*hstepm matrices. 
                   3678:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3679:      (typically every 2 years instead of every month which is too big 
                   3680:      for the memory).
                   3681:      Model is determined by parameters x and covariates have to be 
                   3682:      included manually here. 
                   3683: 
                   3684:      */
                   3685: 
1.330     brouard  3686:   int i, j, d, h, k, k1;
1.131     brouard  3687:   double **out, cov[NCOVMAX+1];
1.126     brouard  3688:   double **newm;
1.187     brouard  3689:   double agexact;
1.214     brouard  3690:   double agebegin, ageend;
1.126     brouard  3691: 
                   3692:   /* Hstepm could be zero and should return the unit matrix */
                   3693:   for (i=1;i<=nlstate+ndeath;i++)
                   3694:     for (j=1;j<=nlstate+ndeath;j++){
                   3695:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3696:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3697:     }
                   3698:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3699:   for(h=1; h <=nhstepm; h++){
                   3700:     for(d=1; d <=hstepm; d++){
                   3701:       newm=savm;
                   3702:       /* Covariates have to be included here again */
                   3703:       cov[1]=1.;
1.214     brouard  3704:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3705:       cov[2]=agexact;
1.319     brouard  3706:       if(nagesqr==1){
1.227     brouard  3707:        cov[3]= agexact*agexact;
1.319     brouard  3708:       }
1.330     brouard  3709:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3710:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3711:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3712:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3713:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3714:        }else{
                   3715:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3716:        }
                   3717:       }/* End of loop on model equation */
                   3718:        /* Old code */ 
                   3719: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3720: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3721: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3722: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3723: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3724: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3725: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3726: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3727: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3728: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3729: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3730: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3731: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3732: /*       /\* 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]])); *\/ */
                   3733: /*       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); */
                   3734: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3735: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3736: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3737: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3738: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3739: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3740: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3741: /*       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]]); */
                   3742: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3743: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3744: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3745: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3746: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3747: /*       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]); */
                   3748: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3749: 
                   3750: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3751: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3752: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3753: /*       /\* *\/ */
1.330     brouard  3754: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3755: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3756: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3757: /* /\*cptcovage=2                   1               2      *\/ */
                   3758: /* /\*Tage[k]=                      5               8      *\/  */
                   3759: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3760: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3761: /*       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]]); */
                   3762: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3763: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3764: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3765: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3766: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3767: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3768: /*       /\*   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); *\/ */
                   3769: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3770: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3771: /*       /\* } *\/ */
                   3772: /*       /\* 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]); *\/ */
                   3773: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3774: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3775: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3776: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3777: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3778: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3779: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3780: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3781: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3782:          
1.332     brouard  3783: /*       /\* 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])]); *\/ */
                   3784: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3785: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3786: /*       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]]); */
                   3787: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3788: 
                   3789: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3790: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3791: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3792: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3793: /*           /\* 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]])]; *\/ */
                   3794: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3795: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3796: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3797: /*       /\*   } *\/ */
                   3798: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3799: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3800: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3801: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3802: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3803: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3804: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3805: /*       /\*   } *\/ */
                   3806: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3807: /*     }/\*end of products *\/ */
                   3808:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3809:       /* for (k=1; k<=cptcovn;k++)  */
                   3810:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3811:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3812:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3813:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3814:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3815:       
                   3816:       
1.126     brouard  3817:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3818:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3819:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3820:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3821:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3822:       /* if((int)age == 70){ */
                   3823:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3824:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3825:       /*         printf("%d pmmij ",i); */
                   3826:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3827:       /*           printf("%f ",pmmij[i][j]); */
                   3828:       /*         } */
                   3829:       /*         printf(" oldm "); */
                   3830:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3831:       /*           printf("%f ",oldm[i][j]); */
                   3832:       /*         } */
                   3833:       /*         printf("\n"); */
                   3834:       /*       } */
                   3835:       /* } */
1.126     brouard  3836:       savm=oldm;
                   3837:       oldm=newm;
                   3838:     }
                   3839:     for(i=1; i<=nlstate+ndeath; i++)
                   3840:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3841:        po[i][j][h]=newm[i][j];
                   3842:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3843:       }
1.128     brouard  3844:     /*printf("h=%d ",h);*/
1.126     brouard  3845:   } /* end h */
1.267     brouard  3846:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3847:   return po;
                   3848: }
                   3849: 
1.217     brouard  3850: /************* Higher Back Matrix Product ***************/
1.218     brouard  3851: /* 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  3852: 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  3853: {
1.332     brouard  3854:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3855:      computes the transition matrix starting at age 'age' over
1.217     brouard  3856:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3857:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3858:      nhstepm*hstepm matrices.
                   3859:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3860:      (typically every 2 years instead of every month which is too big
1.217     brouard  3861:      for the memory).
1.218     brouard  3862:      Model is determined by parameters x and covariates have to be
1.266     brouard  3863:      included manually here. Then we use a call to bmij(x and cov)
                   3864:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3865:   */
1.217     brouard  3866: 
1.332     brouard  3867:   int i, j, d, h, k, k1;
1.266     brouard  3868:   double **out, cov[NCOVMAX+1], **bmij();
                   3869:   double **newm, ***newmm;
1.217     brouard  3870:   double agexact;
                   3871:   double agebegin, ageend;
1.222     brouard  3872:   double **oldm, **savm;
1.217     brouard  3873: 
1.266     brouard  3874:   newmm=po; /* To be saved */
                   3875:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3876:   /* Hstepm could be zero and should return the unit matrix */
                   3877:   for (i=1;i<=nlstate+ndeath;i++)
                   3878:     for (j=1;j<=nlstate+ndeath;j++){
                   3879:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3880:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3881:     }
                   3882:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3883:   for(h=1; h <=nhstepm; h++){
                   3884:     for(d=1; d <=hstepm; d++){
                   3885:       newm=savm;
                   3886:       /* Covariates have to be included here again */
                   3887:       cov[1]=1.;
1.271     brouard  3888:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3889:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3890:         /* Debug */
                   3891:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3892:       cov[2]=agexact;
1.332     brouard  3893:       if(nagesqr==1){
1.222     brouard  3894:        cov[3]= agexact*agexact;
1.332     brouard  3895:       }
                   3896:       /** New code */
                   3897:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3898:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3899:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3900:        }else{
1.332     brouard  3901:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3902:        }
1.332     brouard  3903:       }/* End of loop on model equation */
                   3904:       /** End of new code */
                   3905:   /** This was old code */
                   3906:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3907:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3908:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3909:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3910:       /*   /\* 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)); *\/ */
                   3911:       /* } */
                   3912:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3913:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3914:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3915:       /*       /\* 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]); *\/ */
                   3916:       /* } */
                   3917:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3918:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3919:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3920:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3921:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3922:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3923:       /*       } */
                   3924:       /*       /\* 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]); *\/ */
                   3925:       /* } */
                   3926:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3927:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3928:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3929:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3930:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3931:       /*         }else{ */
                   3932:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3933:       /*         } */
                   3934:       /*       }else{ */
                   3935:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3936:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3937:       /*         }else{ */
                   3938:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3939:       /*         } */
                   3940:       /*       } */
                   3941:       /* }                      */
                   3942:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3943:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3944: /** End of old code */
                   3945:       
1.218     brouard  3946:       /* Careful transposed matrix */
1.266     brouard  3947:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3948:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3949:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3950:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3951:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3952:       /* if((int)age == 70){ */
                   3953:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3954:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3955:       /*         printf("%d pmmij ",i); */
                   3956:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3957:       /*           printf("%f ",pmmij[i][j]); */
                   3958:       /*         } */
                   3959:       /*         printf(" oldm "); */
                   3960:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3961:       /*           printf("%f ",oldm[i][j]); */
                   3962:       /*         } */
                   3963:       /*         printf("\n"); */
                   3964:       /*       } */
                   3965:       /* } */
                   3966:       savm=oldm;
                   3967:       oldm=newm;
                   3968:     }
                   3969:     for(i=1; i<=nlstate+ndeath; i++)
                   3970:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3971:        po[i][j][h]=newm[i][j];
1.268     brouard  3972:        /* if(h==nhstepm) */
                   3973:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3974:       }
1.268     brouard  3975:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3976:   } /* end h */
1.268     brouard  3977:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3978:   return po;
                   3979: }
                   3980: 
                   3981: 
1.162     brouard  3982: #ifdef NLOPT
                   3983:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3984:   double fret;
                   3985:   double *xt;
                   3986:   int j;
                   3987:   myfunc_data *d2 = (myfunc_data *) pd;
                   3988: /* xt = (p1-1); */
                   3989:   xt=vector(1,n); 
                   3990:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3991: 
                   3992:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3993:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3994:   printf("Function = %.12lf ",fret);
                   3995:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3996:   printf("\n");
                   3997:  free_vector(xt,1,n);
                   3998:   return fret;
                   3999: }
                   4000: #endif
1.126     brouard  4001: 
                   4002: /*************** log-likelihood *************/
                   4003: double func( double *x)
                   4004: {
1.336     brouard  4005:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  4006:   int ioffset=0;
1.339     brouard  4007:   int ipos=0,iposold=0,ncovv=0;
                   4008: 
1.340     brouard  4009:   double cotvarv, cotvarvold;
1.226     brouard  4010:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4011:   double **out;
                   4012:   double lli; /* Individual log likelihood */
                   4013:   int s1, s2;
1.228     brouard  4014:   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  4015: 
1.226     brouard  4016:   double bbh, survp;
                   4017:   double agexact;
1.336     brouard  4018:   double agebegin, ageend;
1.226     brouard  4019:   /*extern weight */
                   4020:   /* We are differentiating ll according to initial status */
                   4021:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4022:   /*for(i=1;i<imx;i++) 
                   4023:     printf(" %d\n",s[4][i]);
                   4024:   */
1.162     brouard  4025: 
1.226     brouard  4026:   ++countcallfunc;
1.162     brouard  4027: 
1.226     brouard  4028:   cov[1]=1.;
1.126     brouard  4029: 
1.226     brouard  4030:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4031:   ioffset=0;
1.226     brouard  4032:   if(mle==1){
                   4033:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4034:       /* Computes the values of the ncovmodel covariates of the model
                   4035:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4036:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4037:         to be observed in j being in i according to the model.
                   4038:       */
1.243     brouard  4039:       ioffset=2+nagesqr ;
1.233     brouard  4040:    /* Fixed */
1.345     brouard  4041:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4042:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4043:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4044:        /*  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  4045:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4046:        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  4047:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4048:       }
1.226     brouard  4049:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4050:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4051:         has been calculated etc */
                   4052:       /* For an individual i, wav[i] gives the number of effective waves */
                   4053:       /* We compute the contribution to Likelihood of each effective transition
                   4054:         mw[mi][i] is real wave of the mi th effectve wave */
                   4055:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4056:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4057:         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  4058:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4059:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4060:       */
1.336     brouard  4061:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4062:       /* Wave varying (but not age varying) */
1.339     brouard  4063:        /* 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*\/ */
                   4064:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4065:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4066:        /* } */
1.340     brouard  4067:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4068:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4069:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4070:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4071:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4072:          }else{ /* fixed covariate */
1.345     brouard  4073:            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  4074:          }
1.339     brouard  4075:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4076:            cotvarvold=cotvarv;
                   4077:          }else{ /* A second product */
                   4078:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4079:          }
                   4080:          iposold=ipos;
1.340     brouard  4081:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4082:        }
1.339     brouard  4083:        /* for products of time varying to be done */
1.234     brouard  4084:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4085:          for (j=1;j<=nlstate+ndeath;j++){
                   4086:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4087:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4088:          }
1.336     brouard  4089: 
                   4090:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4091:        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  4092:        for(d=0; d<dh[mi][i]; d++){
                   4093:          newm=savm;
                   4094:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4095:          cov[2]=agexact;
                   4096:          if(nagesqr==1)
                   4097:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4098:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4099:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4100:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4101:          /*   else */
                   4102:          /*     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) *\/  */
                   4103:          /* } */
                   4104:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4105:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4106:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4107:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4108:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4109:            }else{ /* fixed covariate */
                   4110:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4111:            }
                   4112:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4113:              cotvarvold=cotvarv;
                   4114:            }else{ /* A second product */
                   4115:              cotvarv=cotvarv*cotvarvold;
                   4116:            }
                   4117:            iposold=ipos;
                   4118:            cov[ioffset+ipos]=cotvarv*agexact;
                   4119:            /* For products */
1.234     brouard  4120:          }
1.349     brouard  4121:          
1.234     brouard  4122:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4123:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4124:          savm=oldm;
                   4125:          oldm=newm;
                   4126:        } /* end mult */
                   4127:        
                   4128:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4129:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4130:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4131:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4132:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4133:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4134:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4135:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4136:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4137:                                 * -stepm/2 to stepm/2 .
                   4138:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4139:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4140:                                 */
1.234     brouard  4141:        s1=s[mw[mi][i]][i];
                   4142:        s2=s[mw[mi+1][i]][i];
                   4143:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4144:        /* bias bh is positive if real duration
                   4145:         * is higher than the multiple of stepm and negative otherwise.
                   4146:         */
                   4147:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4148:        if( s2 > nlstate){ 
                   4149:          /* i.e. if s2 is a death state and if the date of death is known 
                   4150:             then the contribution to the likelihood is the probability to 
                   4151:             die between last step unit time and current  step unit time, 
                   4152:             which is also equal to probability to die before dh 
                   4153:             minus probability to die before dh-stepm . 
                   4154:             In version up to 0.92 likelihood was computed
                   4155:             as if date of death was unknown. Death was treated as any other
                   4156:             health state: the date of the interview describes the actual state
                   4157:             and not the date of a change in health state. The former idea was
                   4158:             to consider that at each interview the state was recorded
                   4159:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4160:             introduced the exact date of death then we should have modified
                   4161:             the contribution of an exact death to the likelihood. This new
                   4162:             contribution is smaller and very dependent of the step unit
                   4163:             stepm. It is no more the probability to die between last interview
                   4164:             and month of death but the probability to survive from last
                   4165:             interview up to one month before death multiplied by the
                   4166:             probability to die within a month. Thanks to Chris
                   4167:             Jackson for correcting this bug.  Former versions increased
                   4168:             mortality artificially. The bad side is that we add another loop
                   4169:             which slows down the processing. The difference can be up to 10%
                   4170:             lower mortality.
                   4171:          */
                   4172:          /* If, at the beginning of the maximization mostly, the
                   4173:             cumulative probability or probability to be dead is
                   4174:             constant (ie = 1) over time d, the difference is equal to
                   4175:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4176:             s1 at precedent wave, to be dead a month before current
                   4177:             wave is equal to probability, being at state s1 at
                   4178:             precedent wave, to be dead at mont of the current
                   4179:             wave. Then the observed probability (that this person died)
                   4180:             is null according to current estimated parameter. In fact,
                   4181:             it should be very low but not zero otherwise the log go to
                   4182:             infinity.
                   4183:          */
1.183     brouard  4184: /* #ifdef INFINITYORIGINAL */
                   4185: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4186: /* #else */
                   4187: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4188: /*         lli=log(mytinydouble); */
                   4189: /*       else */
                   4190: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4191: /* #endif */
1.226     brouard  4192:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4193:          
1.226     brouard  4194:        } else if  ( s2==-1 ) { /* alive */
                   4195:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4196:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4197:          /*survp += out[s1][j]; */
                   4198:          lli= log(survp);
                   4199:        }
1.336     brouard  4200:        /* else if  (s2==-4) {  */
                   4201:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4202:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4203:        /*   lli= log(survp);  */
                   4204:        /* }  */
                   4205:        /* else if  (s2==-5) {  */
                   4206:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4207:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4208:        /*   lli= log(survp);  */
                   4209:        /* }  */
1.226     brouard  4210:        else{
                   4211:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4212:          /*  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 */
                   4213:        } 
                   4214:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4215:        /*if(lli ==000.0)*/
1.340     brouard  4216:        /* 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  4217:        ipmx +=1;
                   4218:        sw += weight[i];
                   4219:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4220:        /* if (lli < log(mytinydouble)){ */
                   4221:        /*   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); */
                   4222:        /*   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]); */
                   4223:        /* } */
                   4224:       } /* end of wave */
                   4225:     } /* end of individual */
                   4226:   }  else if(mle==2){
                   4227:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4228:       ioffset=2+nagesqr ;
                   4229:       for (k=1; k<=ncovf;k++)
                   4230:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4231:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4232:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4233:          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  4234:        }
1.226     brouard  4235:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4236:          for (j=1;j<=nlstate+ndeath;j++){
                   4237:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4238:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4239:          }
                   4240:        for(d=0; d<=dh[mi][i]; d++){
                   4241:          newm=savm;
                   4242:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4243:          cov[2]=agexact;
                   4244:          if(nagesqr==1)
                   4245:            cov[3]= agexact*agexact;
                   4246:          for (kk=1; kk<=cptcovage;kk++) {
                   4247:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4248:          }
                   4249:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4250:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4251:          savm=oldm;
                   4252:          oldm=newm;
                   4253:        } /* end mult */
                   4254:       
                   4255:        s1=s[mw[mi][i]][i];
                   4256:        s2=s[mw[mi+1][i]][i];
                   4257:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4258:        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 */
                   4259:        ipmx +=1;
                   4260:        sw += weight[i];
                   4261:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4262:       } /* end of wave */
                   4263:     } /* end of individual */
                   4264:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4265:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4266:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4267:       for(mi=1; mi<= wav[i]-1; mi++){
                   4268:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4269:          for (j=1;j<=nlstate+ndeath;j++){
                   4270:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4271:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4272:          }
                   4273:        for(d=0; d<dh[mi][i]; d++){
                   4274:          newm=savm;
                   4275:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4276:          cov[2]=agexact;
                   4277:          if(nagesqr==1)
                   4278:            cov[3]= agexact*agexact;
                   4279:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4280:            if(!FixedV[Tvar[Tage[kk]]])
                   4281:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4282:            else
1.341     brouard  4283:              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  4284:          }
                   4285:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4286:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4287:          savm=oldm;
                   4288:          oldm=newm;
                   4289:        } /* end mult */
                   4290:       
                   4291:        s1=s[mw[mi][i]][i];
                   4292:        s2=s[mw[mi+1][i]][i];
                   4293:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4294:        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 */
                   4295:        ipmx +=1;
                   4296:        sw += weight[i];
                   4297:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4298:       } /* end of wave */
                   4299:     } /* end of individual */
                   4300:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4301:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4302:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4303:       for(mi=1; mi<= wav[i]-1; mi++){
                   4304:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4305:          for (j=1;j<=nlstate+ndeath;j++){
                   4306:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4307:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4308:          }
                   4309:        for(d=0; d<dh[mi][i]; d++){
                   4310:          newm=savm;
                   4311:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4312:          cov[2]=agexact;
                   4313:          if(nagesqr==1)
                   4314:            cov[3]= agexact*agexact;
                   4315:          for (kk=1; kk<=cptcovage;kk++) {
                   4316:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4317:          }
1.126     brouard  4318:        
1.226     brouard  4319:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4320:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4321:          savm=oldm;
                   4322:          oldm=newm;
                   4323:        } /* end mult */
                   4324:       
                   4325:        s1=s[mw[mi][i]][i];
                   4326:        s2=s[mw[mi+1][i]][i];
                   4327:        if( s2 > nlstate){ 
                   4328:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4329:        } else if  ( s2==-1 ) { /* alive */
                   4330:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4331:            survp += out[s1][j];
                   4332:          lli= log(survp);
                   4333:        }else{
                   4334:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4335:        }
                   4336:        ipmx +=1;
                   4337:        sw += weight[i];
                   4338:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4339:        /* 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  4340:       } /* end of wave */
                   4341:     } /* end of individual */
                   4342:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4343:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4344:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4345:       for(mi=1; mi<= wav[i]-1; mi++){
                   4346:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4347:          for (j=1;j<=nlstate+ndeath;j++){
                   4348:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4349:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4350:          }
                   4351:        for(d=0; d<dh[mi][i]; d++){
                   4352:          newm=savm;
                   4353:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4354:          cov[2]=agexact;
                   4355:          if(nagesqr==1)
                   4356:            cov[3]= agexact*agexact;
                   4357:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4358:            if(!FixedV[Tvar[Tage[kk]]])
                   4359:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4360:            else
1.341     brouard  4361:              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  4362:          }
1.126     brouard  4363:        
1.226     brouard  4364:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4365:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4366:          savm=oldm;
                   4367:          oldm=newm;
                   4368:        } /* end mult */
                   4369:       
                   4370:        s1=s[mw[mi][i]][i];
                   4371:        s2=s[mw[mi+1][i]][i];
                   4372:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4373:        ipmx +=1;
                   4374:        sw += weight[i];
                   4375:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4376:        /*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]);*/
                   4377:       } /* end of wave */
                   4378:     } /* end of individual */
                   4379:   } /* End of if */
                   4380:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4381:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4382:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4383:   return -l;
1.126     brouard  4384: }
                   4385: 
                   4386: /*************** log-likelihood *************/
                   4387: double funcone( double *x)
                   4388: {
1.228     brouard  4389:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4390:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4391:   int ioffset=0;
1.339     brouard  4392:   int ipos=0,iposold=0,ncovv=0;
                   4393: 
1.340     brouard  4394:   double cotvarv, cotvarvold;
1.131     brouard  4395:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4396:   double **out;
                   4397:   double lli; /* Individual log likelihood */
                   4398:   double llt;
                   4399:   int s1, s2;
1.228     brouard  4400:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4401: 
1.126     brouard  4402:   double bbh, survp;
1.187     brouard  4403:   double agexact;
1.214     brouard  4404:   double agebegin, ageend;
1.126     brouard  4405:   /*extern weight */
                   4406:   /* We are differentiating ll according to initial status */
                   4407:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4408:   /*for(i=1;i<imx;i++) 
                   4409:     printf(" %d\n",s[4][i]);
                   4410:   */
                   4411:   cov[1]=1.;
                   4412: 
                   4413:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4414:   ioffset=0;
                   4415:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4416:     /* Computes the values of the ncovmodel covariates of the model
                   4417:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4418:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4419:        to be observed in j being in i according to the model.
                   4420:     */
1.243     brouard  4421:     /* ioffset=2+nagesqr+cptcovage; */
                   4422:     ioffset=2+nagesqr;
1.232     brouard  4423:     /* Fixed */
1.224     brouard  4424:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4425:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4426:     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  4427:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4428:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4429:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4430:       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  4431: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4432: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4433: /*    cov[2+6]=covar[2][i]; V2  */
                   4434: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4435: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4436: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4437: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4438: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4439: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4440:     }
1.336     brouard  4441:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4442:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4443:         has been calculated etc */
                   4444:       /* For an individual i, wav[i] gives the number of effective waves */
                   4445:       /* We compute the contribution to Likelihood of each effective transition
                   4446:         mw[mi][i] is real wave of the mi th effectve wave */
                   4447:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4448:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4449:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4450:       */
                   4451:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4452:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4453:     /*   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?)*\/ */
                   4454:     /* } */
1.231     brouard  4455:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4456:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4457:     /* } */
1.225     brouard  4458:     
1.233     brouard  4459: 
                   4460:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4461:       /* 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 */
                   4462:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4463:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4464:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4465:       /* } */
                   4466:       
                   4467:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4468:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4469:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4470:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4471:       /* We need the position of the time varying or product in the model */
                   4472:       /* 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 */            
                   4473:       /* TvarVV gives the variable name */
1.340     brouard  4474:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4475:       *      k=         1   2     3     4         5        6        7       8        9
                   4476:       *  varying            1     2                                 3       4        5
                   4477:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4478:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4479:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4480:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4481:       */
1.345     brouard  4482:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4483:        * 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  4484:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4485:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4486:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4487:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4488:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4489:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4490:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4491:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4492:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4493:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4494:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4495:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4496:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4497:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4498:        *                  12       13      14      15       16
                   4499:        *                    17        18         19        20         21
                   4500:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4501:        *                   2       3        4       6        7
                   4502:        *                     9         11          12        13         14            
                   4503:        * cptcovage=5+5 total of covariates with age 
                   4504:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4505:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4506:        *3 Tage[cptcovage] age*V3*V2=6  
                   4507:        *3                age*V2=12         13      14      15       16
                   4508:        *3                age*V6*V3=18      19    20   21
                   4509:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4510:        *     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
                   4511:        * 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
                   4512:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4513:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4514:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4515:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4516:        * 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
                   4517:        * Tvar=                {2, 3, 4, 6, 7,
                   4518:        *                       9, 10, 11, 12, 13, 14,
                   4519:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4520:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4521:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4522:        *                  2, 2, 2, 2, 2, 2,
                   4523:        * 3                3, 2, 2, 2, 2, 2,
                   4524:        *                  1, 1, 1, 1, 1, 
                   4525:        *                  3, 3, 3, 3, 3}
                   4526:        * 3                 2, 3, 3, 3, 3}
                   4527:        * 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
                   4528:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4529:        * 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}
                   4530:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4531:        * cptcovprod=11 (6+5)
                   4532:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4533:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4534:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4535:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4536:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4537:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4538:        * cptcovdageprod=5  for gnuplot printing
                   4539:        * cptcovprodvage=6 
                   4540:        * ncova=15           1        2       3       4       5
                   4541:        *                      6 7        8 9      10 11        12 13     14 15
                   4542:        * TvarA              2        3       4       6       7
                   4543:        *                      6 2        6 7       7 3          6 4       7 4
                   4544:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4545:        * ncovf            1     2      3
1.349     brouard  4546:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4547:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4548:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4549:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4550:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4551:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4552:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4553:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4554:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4555:        * 3 cptcovprodvage=6
                   4556:        * 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
                   4557:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4558:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  4559:        *?TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
1.349     brouard  4560:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4561:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4562:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4563:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4564:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4565:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4566:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4567:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4568:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4569:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4570:        *                   2, 3, 4, 6, 7,
                   4571:        *                     6, 8, 9, 10, 11}
1.345     brouard  4572:        * TvarFind[itv]                        0      0       0
                   4573:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  4574:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  4575:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4576:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4577:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4578:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4579:        */
                   4580: 
1.349     brouard  4581:       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 */
                   4582:        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  4583:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4584:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4585:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
1.354     brouard  4586:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  4587:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  4588:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4589:        }else{ /* fixed covariate */
1.345     brouard  4590:          /* 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.354     brouard  4591:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  4592:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  4593:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4594:        }
1.339     brouard  4595:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4596:          cotvarvold=cotvarv;
                   4597:        }else{ /* A second product */
                   4598:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4599:        }
                   4600:        iposold=ipos;
1.340     brouard  4601:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  4602:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  4603:        /* For products */
                   4604:       }
                   4605:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4606:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4607:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4608:       /*       /\*           1  2   3      4      5                         *\/ */
                   4609:       /*       /\*itv           1                                           *\/ */
                   4610:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4611:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4612:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4613:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4614:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4615:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4616:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4617:       /*       /\* 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]); *\/ */
                   4618:       /* } */
1.232     brouard  4619:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4620:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4621:       /*       /\* 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]); *\/ */
                   4622:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4623:       /* } */
1.126     brouard  4624:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4625:        for (j=1;j<=nlstate+ndeath;j++){
                   4626:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4627:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4628:        }
1.214     brouard  4629:       
                   4630:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4631:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4632:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4633:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4634:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4635:          and mw[mi+1][i]. dh depends on stepm.*/
                   4636:        newm=savm;
1.247     brouard  4637:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4638:        cov[2]=agexact;
                   4639:        if(nagesqr==1)
                   4640:          cov[3]= agexact*agexact;
1.349     brouard  4641:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4642:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4643:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4644:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4645:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4646:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4647:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4648:          }else{ /* fixed covariate */
                   4649:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4650:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4651:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4652:          }
                   4653:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4654:            cotvarvold=cotvarv;
                   4655:          }else{ /* A second product */
                   4656:            /* printf("DEBUG * \n"); */
                   4657:            cotvarv=cotvarv*cotvarvold;
                   4658:          }
                   4659:          iposold=ipos;
                   4660:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4661:          cov[ioffset+ipos]=cotvarv*agexact;
                   4662:          /* For products */
1.242     brouard  4663:        }
1.349     brouard  4664: 
1.242     brouard  4665:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4666:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4667:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4668:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4669:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4670:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4671:        savm=oldm;
                   4672:        oldm=newm;
1.126     brouard  4673:       } /* end mult */
1.336     brouard  4674:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4675:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4676:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4677:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4678:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4679:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4680:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4681:         * probability in order to take into account the bias as a fraction of the way
                   4682:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4683:                                 * -stepm/2 to stepm/2 .
                   4684:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4685:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4686:                                 */
1.126     brouard  4687:       s1=s[mw[mi][i]][i];
                   4688:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4689:       /* if(s2==-1){ */
1.268     brouard  4690:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4691:       /*       /\* exit(1); *\/ */
                   4692:       /* } */
1.126     brouard  4693:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4694:       /* bias is positive if real duration
                   4695:        * is higher than the multiple of stepm and negative otherwise.
                   4696:        */
                   4697:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4698:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4699:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4700:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4701:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4702:        lli= log(survp);
1.126     brouard  4703:       }else if (mle==1){
1.242     brouard  4704:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4705:       } else if(mle==2){
1.242     brouard  4706:        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  4707:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4708:        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  4709:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4710:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4711:       } else{  /* mle=0 back to 1 */
1.242     brouard  4712:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4713:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4714:       } /* End of if */
                   4715:       ipmx +=1;
                   4716:       sw += weight[i];
                   4717:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4718:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4719:       /* 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  4720:       if(globpr){
1.246     brouard  4721:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4722:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4723:                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  4724:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4725:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4726:        /* %11.6f %11.6f %11.6f ", \ */
                   4727:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4728:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4729:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4730:          llt +=ll[k]*gipmx/gsw;
                   4731:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4732:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4733:        }
1.343     brouard  4734:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4735:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4736:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4737:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4738:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4739:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4740:        }
                   4741:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4742:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4743:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4744:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4745:            /* printf(" %g",cov[ioffset+ipos]); */
                   4746:          }else{
                   4747:            fprintf(ficresilk,"*");
                   4748:            /* printf("*"); */
1.342     brouard  4749:          }
1.343     brouard  4750:          iposold=ipos;
                   4751:        }
1.349     brouard  4752:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4753:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4754:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4755:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4756:        /*   }else{ */
                   4757:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4758:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4759:        /*   } */
                   4760:        /* } */
                   4761:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4762:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4763:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4764:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4765:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4766:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4767:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4768:          }else{ /* fixed covariate */
                   4769:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4770:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4771:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4772:          }
                   4773:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4774:            cotvarvold=cotvarv;
                   4775:          }else{ /* A second product */
                   4776:            /* printf("DEBUG * \n"); */
                   4777:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4778:          }
1.349     brouard  4779:          cotvarv=cotvarv*agexact;
                   4780:          fprintf(ficresilk," %g*age",cotvarv);
                   4781:          iposold=ipos;
                   4782:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4783:          cov[ioffset+ipos]=cotvarv;
                   4784:          /* For products */
1.343     brouard  4785:        }
                   4786:        /* printf("\n"); */
1.342     brouard  4787:        /* } /\*  End debugILK *\/ */
                   4788:        fprintf(ficresilk,"\n");
                   4789:       } /* End if globpr */
1.335     brouard  4790:     } /* end of wave */
                   4791:   } /* end of individual */
                   4792:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4793: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4794:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4795:   if(globpr==0){ /* First time we count the contributions and weights */
                   4796:     gipmx=ipmx;
                   4797:     gsw=sw;
                   4798:   }
1.343     brouard  4799:   return -l;
1.126     brouard  4800: }
                   4801: 
                   4802: 
                   4803: /*************** function likelione ***********/
1.292     brouard  4804: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4805: {
                   4806:   /* This routine should help understanding what is done with 
                   4807:      the selection of individuals/waves and
                   4808:      to check the exact contribution to the likelihood.
                   4809:      Plotting could be done.
1.342     brouard  4810:   */
                   4811:   void pstamp(FILE *ficres);
1.343     brouard  4812:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4813: 
                   4814:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4815:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4816:     strcat(fileresilk,fileresu);
1.126     brouard  4817:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4818:       printf("Problem with resultfile: %s\n", fileresilk);
                   4819:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4820:     }
1.342     brouard  4821:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4822:     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");
                   4823:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4824:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4825:     for(k=1; k<=nlstate; k++) 
                   4826:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4827:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4828: 
                   4829:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4830:       for(kf=1;kf <= ncovf; kf++){
                   4831:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4832:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4833:       }
                   4834:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4835:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4836:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4837:          /* printf(" %d",ipos); */
                   4838:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4839:        }else{
                   4840:          /* printf("*"); */
                   4841:          fprintf(ficresilk,"*");
1.343     brouard  4842:        }
1.342     brouard  4843:        iposold=ipos;
                   4844:       }
                   4845:       for (kk=1; kk<=cptcovage;kk++) {
                   4846:        if(!FixedV[Tvar[Tage[kk]]]){
                   4847:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4848:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4849:        }else{
                   4850:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4851:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4852:        }
                   4853:       }
                   4854:     /* } /\* End if debugILK *\/ */
                   4855:     /* printf("\n"); */
                   4856:     fprintf(ficresilk,"\n");
                   4857:   } /* End glogpri */
1.126     brouard  4858: 
1.292     brouard  4859:   *fretone=(*func)(p);
1.126     brouard  4860:   if(*globpri !=0){
                   4861:     fclose(ficresilk);
1.205     brouard  4862:     if (mle ==0)
                   4863:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4864:     else if(mle >=1)
                   4865:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4866:     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  4867:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4868:       
1.207     brouard  4869:     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  4870: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4871:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4872: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4873:     
                   4874:     for (k=1; k<= nlstate ; k++) {
                   4875:       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 \
                   4876: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4877:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  4878:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   4879:         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]]);
                   4880:         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);
                   4881:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4882:       }
                   4883:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4884:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4885:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4886:        /* 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]); */
                   4887:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4888:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4889:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4890:          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)  */
                   4891:            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> \
                   4892: <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);
                   4893:          } /* End only for dummies time varying (single?) */
                   4894:        }else{ /* Useless product */
                   4895:          /* printf("*"); */
                   4896:          /* fprintf(ficresilk,"*"); */ 
                   4897:        }
                   4898:        iposold=ipos;
                   4899:       } /* For each time varying covariate */
                   4900:     } /* End loop on states */
                   4901: 
                   4902: /*     if(debugILK){ */
                   4903: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4904: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4905: /*     for (k=1; k<= nlstate ; k++) { */
                   4906: /*       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> \ */
                   4907: /* <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]]); */
                   4908: /*     } */
                   4909: /*       } */
                   4910: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4911: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4912: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4913: /*     /\* 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]); *\/ */
                   4914: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4915: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4916: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4917: /*       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)  *\/ */
                   4918: /*         for (k=1; k<= nlstate ; k++) { */
                   4919: /*           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> \ */
                   4920: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4921: /*         } /\* End state *\/ */
                   4922: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4923: /*     }else{ /\* Useless product *\/ */
                   4924: /*       /\* printf("*"); *\/ */
                   4925: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4926: /*     } */
                   4927: /*     iposold=ipos; */
                   4928: /*       } /\* For each time varying covariate *\/ */
                   4929: /*     }/\* End debugILK *\/ */
1.207     brouard  4930:     fflush(fichtm);
1.343     brouard  4931:   }/* End globpri */
1.126     brouard  4932:   return;
                   4933: }
                   4934: 
                   4935: 
                   4936: /*********** Maximum Likelihood Estimation ***************/
                   4937: 
                   4938: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4939: {
1.319     brouard  4940:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4941:   double **xi;
                   4942:   double fret;
                   4943:   double fretone; /* Only one call to likelihood */
                   4944:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  4945:   
                   4946:   double * p1; /* Shifted parameters from 0 instead of 1 */
1.162     brouard  4947: #ifdef NLOPT
                   4948:   int creturn;
                   4949:   nlopt_opt opt;
                   4950:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4951:   double *lb;
                   4952:   double minf; /* the minimum objective value, upon return */
1.354     brouard  4953: 
1.162     brouard  4954:   myfunc_data dinst, *d = &dinst;
                   4955: #endif
                   4956: 
                   4957: 
1.126     brouard  4958:   xi=matrix(1,npar,1,npar);
                   4959:   for (i=1;i<=npar;i++)
                   4960:     for (j=1;j<=npar;j++)
                   4961:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4962:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4963:   strcpy(filerespow,"POW_"); 
1.126     brouard  4964:   strcat(filerespow,fileres);
                   4965:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4966:     printf("Problem with resultfile: %s\n", filerespow);
                   4967:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4968:   }
                   4969:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4970:   for (i=1;i<=nlstate;i++)
                   4971:     for(j=1;j<=nlstate+ndeath;j++)
                   4972:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4973:   fprintf(ficrespow,"\n");
1.162     brouard  4974: #ifdef POWELL
1.319     brouard  4975: #ifdef LINMINORIGINAL
                   4976: #else /* LINMINORIGINAL */
                   4977:   
                   4978:   flatdir=ivector(1,npar); 
                   4979:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4980: #endif /*LINMINORIGINAL */
                   4981: 
                   4982: #ifdef FLATSUP
                   4983:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4984:   /* reorganizing p by suppressing flat directions */
                   4985:   for(i=1, jk=1; i <=nlstate; i++){
                   4986:     for(k=1; k <=(nlstate+ndeath); k++){
                   4987:       if (k != i) {
                   4988:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4989:         if(flatdir[jk]==1){
                   4990:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4991:         }
                   4992:         for(j=1; j <=ncovmodel; j++){
                   4993:           printf("%12.7f ",p[jk]);
                   4994:           jk++; 
                   4995:         }
                   4996:         printf("\n");
                   4997:       }
                   4998:     }
                   4999:   }
                   5000: /* skipping */
                   5001:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   5002:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   5003:     for(k=1; k <=(nlstate+ndeath); k++){
                   5004:       if (k != i) {
                   5005:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5006:         if(flatdir[jk]==1){
                   5007:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   5008:           for(j=1; j <=ncovmodel;  jk++,j++){
                   5009:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   5010:             /*q[jjk]=p[jk];*/
                   5011:           }
                   5012:         }else{
                   5013:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   5014:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   5015:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5016:             /*q[jjk]=p[jk];*/
                   5017:           }
                   5018:         }
                   5019:         printf("\n");
                   5020:       }
                   5021:       fflush(stdout);
                   5022:     }
                   5023:   }
                   5024:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5025: #else  /* FLATSUP */
1.126     brouard  5026:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  5027: #endif  /* FLATSUP */
                   5028: 
                   5029: #ifdef LINMINORIGINAL
                   5030: #else
                   5031:       free_ivector(flatdir,1,npar); 
                   5032: #endif  /* LINMINORIGINAL*/
                   5033: #endif /* POWELL */
1.126     brouard  5034: 
1.162     brouard  5035: #ifdef NLOPT
                   5036: #ifdef NEWUOA
                   5037:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5038: #else
                   5039:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5040: #endif
                   5041:   lb=vector(0,npar-1);
                   5042:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5043:   nlopt_set_lower_bounds(opt, lb);
                   5044:   nlopt_set_initial_step1(opt, 0.1);
                   5045:   
                   5046:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5047:   d->function = func;
                   5048:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5049:   nlopt_set_min_objective(opt, myfunc, d);
                   5050:   nlopt_set_xtol_rel(opt, ftol);
                   5051:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5052:     printf("nlopt failed! %d\n",creturn); 
                   5053:   }
                   5054:   else {
                   5055:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5056:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5057:     iter=1; /* not equal */
                   5058:   }
                   5059:   nlopt_destroy(opt);
                   5060: #endif
1.319     brouard  5061: #ifdef FLATSUP
                   5062:   /* npared = npar -flatd/ncovmodel; */
                   5063:   /* xired= matrix(1,npared,1,npared); */
                   5064:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5065:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5066:   /* free_matrix(xire,1,npared,1,npared); */
                   5067: #else  /* FLATSUP */
                   5068: #endif /* FLATSUP */
1.126     brouard  5069:   free_matrix(xi,1,npar,1,npar);
                   5070:   fclose(ficrespow);
1.203     brouard  5071:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5072:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5073:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5074: 
                   5075: }
                   5076: 
                   5077: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5078: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5079: {
                   5080:   double  **a,**y,*x,pd;
1.203     brouard  5081:   /* double **hess; */
1.164     brouard  5082:   int i, j;
1.126     brouard  5083:   int *indx;
                   5084: 
                   5085:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5086:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5087:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5088:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5089:   double gompertz(double p[]);
1.203     brouard  5090:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5091: 
                   5092:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5093:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5094:   for (i=1;i<=npar;i++){
1.203     brouard  5095:     printf("%d-",i);fflush(stdout);
                   5096:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5097:    
                   5098:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5099:     
                   5100:     /*  printf(" %f ",p[i]);
                   5101:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5102:   }
                   5103:   
                   5104:   for (i=1;i<=npar;i++) {
                   5105:     for (j=1;j<=npar;j++)  {
                   5106:       if (j>i) { 
1.203     brouard  5107:        printf(".%d-%d",i,j);fflush(stdout);
                   5108:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5109:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5110:        
                   5111:        hess[j][i]=hess[i][j];    
                   5112:        /*printf(" %lf ",hess[i][j]);*/
                   5113:       }
                   5114:     }
                   5115:   }
                   5116:   printf("\n");
                   5117:   fprintf(ficlog,"\n");
                   5118: 
                   5119:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5120:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5121:   
                   5122:   a=matrix(1,npar,1,npar);
                   5123:   y=matrix(1,npar,1,npar);
                   5124:   x=vector(1,npar);
                   5125:   indx=ivector(1,npar);
                   5126:   for (i=1;i<=npar;i++)
                   5127:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5128:   ludcmp(a,npar,indx,&pd);
                   5129: 
                   5130:   for (j=1;j<=npar;j++) {
                   5131:     for (i=1;i<=npar;i++) x[i]=0;
                   5132:     x[j]=1;
                   5133:     lubksb(a,npar,indx,x);
                   5134:     for (i=1;i<=npar;i++){ 
                   5135:       matcov[i][j]=x[i];
                   5136:     }
                   5137:   }
                   5138: 
                   5139:   printf("\n#Hessian matrix#\n");
                   5140:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5141:   for (i=1;i<=npar;i++) { 
                   5142:     for (j=1;j<=npar;j++) { 
1.203     brouard  5143:       printf("%.6e ",hess[i][j]);
                   5144:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5145:     }
                   5146:     printf("\n");
                   5147:     fprintf(ficlog,"\n");
                   5148:   }
                   5149: 
1.203     brouard  5150:   /* printf("\n#Covariance matrix#\n"); */
                   5151:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5152:   /* for (i=1;i<=npar;i++) {  */
                   5153:   /*   for (j=1;j<=npar;j++) {  */
                   5154:   /*     printf("%.6e ",matcov[i][j]); */
                   5155:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5156:   /*   } */
                   5157:   /*   printf("\n"); */
                   5158:   /*   fprintf(ficlog,"\n"); */
                   5159:   /* } */
                   5160: 
1.126     brouard  5161:   /* Recompute Inverse */
1.203     brouard  5162:   /* for (i=1;i<=npar;i++) */
                   5163:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5164:   /* ludcmp(a,npar,indx,&pd); */
                   5165: 
                   5166:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5167: 
                   5168:   /* for (j=1;j<=npar;j++) { */
                   5169:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5170:   /*   x[j]=1; */
                   5171:   /*   lubksb(a,npar,indx,x); */
                   5172:   /*   for (i=1;i<=npar;i++){  */
                   5173:   /*     y[i][j]=x[i]; */
                   5174:   /*     printf("%.3e ",y[i][j]); */
                   5175:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5176:   /*   } */
                   5177:   /*   printf("\n"); */
                   5178:   /*   fprintf(ficlog,"\n"); */
                   5179:   /* } */
                   5180: 
                   5181:   /* Verifying the inverse matrix */
                   5182: #ifdef DEBUGHESS
                   5183:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5184: 
1.203     brouard  5185:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5186:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5187: 
                   5188:   for (j=1;j<=npar;j++) {
                   5189:     for (i=1;i<=npar;i++){ 
1.203     brouard  5190:       printf("%.2f ",y[i][j]);
                   5191:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5192:     }
                   5193:     printf("\n");
                   5194:     fprintf(ficlog,"\n");
                   5195:   }
1.203     brouard  5196: #endif
1.126     brouard  5197: 
                   5198:   free_matrix(a,1,npar,1,npar);
                   5199:   free_matrix(y,1,npar,1,npar);
                   5200:   free_vector(x,1,npar);
                   5201:   free_ivector(indx,1,npar);
1.203     brouard  5202:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5203: 
                   5204: 
                   5205: }
                   5206: 
                   5207: /*************** hessian matrix ****************/
                   5208: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5209: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5210:   int i;
                   5211:   int l=1, lmax=20;
1.203     brouard  5212:   double k1,k2, res, fx;
1.132     brouard  5213:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5214:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5215:   int k=0,kmax=10;
                   5216:   double l1;
                   5217: 
                   5218:   fx=func(x);
                   5219:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5220:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5221:     l1=pow(10,l);
                   5222:     delts=delt;
                   5223:     for(k=1 ; k <kmax; k=k+1){
                   5224:       delt = delta*(l1*k);
                   5225:       p2[theta]=x[theta] +delt;
1.145     brouard  5226:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5227:       p2[theta]=x[theta]-delt;
                   5228:       k2=func(p2)-fx;
                   5229:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5230:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5231:       
1.203     brouard  5232: #ifdef DEBUGHESSII
1.126     brouard  5233:       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);
                   5234:       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);
                   5235: #endif
                   5236:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5237:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5238:        k=kmax;
                   5239:       }
                   5240:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5241:        k=kmax; l=lmax*10;
1.126     brouard  5242:       }
                   5243:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5244:        delts=delt;
                   5245:       }
1.203     brouard  5246:     } /* End loop k */
1.126     brouard  5247:   }
                   5248:   delti[theta]=delts;
                   5249:   return res; 
                   5250:   
                   5251: }
                   5252: 
1.203     brouard  5253: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5254: {
                   5255:   int i;
1.164     brouard  5256:   int l=1, lmax=20;
1.126     brouard  5257:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5258:   double p2[MAXPARM+1];
1.203     brouard  5259:   int k, kmax=1;
                   5260:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5261: 
                   5262:   int firstime=0;
1.203     brouard  5263:   
1.126     brouard  5264:   fx=func(x);
1.203     brouard  5265:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5266:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5267:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5268:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5269:     k1=func(p2)-fx;
                   5270:   
1.203     brouard  5271:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5272:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5273:     k2=func(p2)-fx;
                   5274:   
1.203     brouard  5275:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5276:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5277:     k3=func(p2)-fx;
                   5278:   
1.203     brouard  5279:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5280:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5281:     k4=func(p2)-fx;
1.203     brouard  5282:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5283:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5284:       firstime=1;
1.203     brouard  5285:       kmax=kmax+10;
1.208     brouard  5286:     }
                   5287:     if(kmax >=10 || firstime ==1){
1.354     brouard  5288:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  5289:       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);
                   5290:       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  5291:       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);
                   5292:       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);
                   5293:     }
                   5294: #ifdef DEBUGHESSIJ
                   5295:     v1=hess[thetai][thetai];
                   5296:     v2=hess[thetaj][thetaj];
                   5297:     cv12=res;
                   5298:     /* Computing eigen value of Hessian matrix */
                   5299:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5300:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5301:     if ((lc2 <0) || (lc1 <0) ){
                   5302:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5303:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5304:       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);
                   5305:       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);
                   5306:     }
1.126     brouard  5307: #endif
                   5308:   }
                   5309:   return res;
                   5310: }
                   5311: 
1.203     brouard  5312:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5313: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5314: /* { */
                   5315: /*   int i; */
                   5316: /*   int l=1, lmax=20; */
                   5317: /*   double k1,k2,k3,k4,res,fx; */
                   5318: /*   double p2[MAXPARM+1]; */
                   5319: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5320: /*   int k=0,kmax=10; */
                   5321: /*   double l1; */
                   5322:   
                   5323: /*   fx=func(x); */
                   5324: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5325: /*     l1=pow(10,l); */
                   5326: /*     delts=delt; */
                   5327: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5328: /*       delt = delti*(l1*k); */
                   5329: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5330: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5331: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5332: /*       k1=func(p2)-fx; */
                   5333:       
                   5334: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5335: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5336: /*       k2=func(p2)-fx; */
                   5337:       
                   5338: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5339: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5340: /*       k3=func(p2)-fx; */
                   5341:       
                   5342: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5343: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5344: /*       k4=func(p2)-fx; */
                   5345: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5346: /* #ifdef DEBUGHESSIJ */
                   5347: /*       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); */
                   5348: /*       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); */
                   5349: /* #endif */
                   5350: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5351: /*     k=kmax; */
                   5352: /*       } */
                   5353: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5354: /*     k=kmax; l=lmax*10; */
                   5355: /*       } */
                   5356: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5357: /*     delts=delt; */
                   5358: /*       } */
                   5359: /*     } /\* End loop k *\/ */
                   5360: /*   } */
                   5361: /*   delti[theta]=delts; */
                   5362: /*   return res;  */
                   5363: /* } */
                   5364: 
                   5365: 
1.126     brouard  5366: /************** Inverse of matrix **************/
                   5367: void ludcmp(double **a, int n, int *indx, double *d) 
                   5368: { 
                   5369:   int i,imax,j,k; 
                   5370:   double big,dum,sum,temp; 
                   5371:   double *vv; 
                   5372:  
                   5373:   vv=vector(1,n); 
                   5374:   *d=1.0; 
                   5375:   for (i=1;i<=n;i++) { 
                   5376:     big=0.0; 
                   5377:     for (j=1;j<=n;j++) 
                   5378:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5379:     if (big == 0.0){
                   5380:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5381:       for (j=1;j<=n;j++) {
                   5382:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5383:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5384:       }
                   5385:       fflush(ficlog);
                   5386:       fclose(ficlog);
                   5387:       nrerror("Singular matrix in routine ludcmp"); 
                   5388:     }
1.126     brouard  5389:     vv[i]=1.0/big; 
                   5390:   } 
                   5391:   for (j=1;j<=n;j++) { 
                   5392:     for (i=1;i<j;i++) { 
                   5393:       sum=a[i][j]; 
                   5394:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5395:       a[i][j]=sum; 
                   5396:     } 
                   5397:     big=0.0; 
                   5398:     for (i=j;i<=n;i++) { 
                   5399:       sum=a[i][j]; 
                   5400:       for (k=1;k<j;k++) 
                   5401:        sum -= a[i][k]*a[k][j]; 
                   5402:       a[i][j]=sum; 
                   5403:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5404:        big=dum; 
                   5405:        imax=i; 
                   5406:       } 
                   5407:     } 
                   5408:     if (j != imax) { 
                   5409:       for (k=1;k<=n;k++) { 
                   5410:        dum=a[imax][k]; 
                   5411:        a[imax][k]=a[j][k]; 
                   5412:        a[j][k]=dum; 
                   5413:       } 
                   5414:       *d = -(*d); 
                   5415:       vv[imax]=vv[j]; 
                   5416:     } 
                   5417:     indx[j]=imax; 
                   5418:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5419:     if (j != n) { 
                   5420:       dum=1.0/(a[j][j]); 
                   5421:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5422:     } 
                   5423:   } 
                   5424:   free_vector(vv,1,n);  /* Doesn't work */
                   5425: ;
                   5426: } 
                   5427: 
                   5428: void lubksb(double **a, int n, int *indx, double b[]) 
                   5429: { 
                   5430:   int i,ii=0,ip,j; 
                   5431:   double sum; 
                   5432:  
                   5433:   for (i=1;i<=n;i++) { 
                   5434:     ip=indx[i]; 
                   5435:     sum=b[ip]; 
                   5436:     b[ip]=b[i]; 
                   5437:     if (ii) 
                   5438:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5439:     else if (sum) ii=i; 
                   5440:     b[i]=sum; 
                   5441:   } 
                   5442:   for (i=n;i>=1;i--) { 
                   5443:     sum=b[i]; 
                   5444:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5445:     b[i]=sum/a[i][i]; 
                   5446:   } 
                   5447: } 
                   5448: 
                   5449: void pstamp(FILE *fichier)
                   5450: {
1.196     brouard  5451:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5452: }
                   5453: 
1.297     brouard  5454: void date2dmy(double date,double *day, double *month, double *year){
                   5455:   double yp=0., yp1=0., yp2=0.;
                   5456:   
                   5457:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5458:                        fractional in yp1 */
                   5459:   *year=yp;
                   5460:   yp2=modf((yp1*12),&yp);
                   5461:   *month=yp;
                   5462:   yp1=modf((yp2*30.5),&yp);
                   5463:   *day=yp;
                   5464:   if(*day==0) *day=1;
                   5465:   if(*month==0) *month=1;
                   5466: }
                   5467: 
1.253     brouard  5468: 
                   5469: 
1.126     brouard  5470: /************ Frequencies ********************/
1.251     brouard  5471: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5472:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5473:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5474: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5475:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5476:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5477:   int iind=0, iage=0;
                   5478:   int mi; /* Effective wave */
                   5479:   int first;
                   5480:   double ***freq; /* Frequencies */
1.268     brouard  5481:   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 */
                   5482:   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  5483:   double *meanq, *stdq, *idq;
1.226     brouard  5484:   double **meanqt;
                   5485:   double *pp, **prop, *posprop, *pospropt;
                   5486:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5487:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5488:   double agebegin, ageend;
                   5489:     
                   5490:   pp=vector(1,nlstate);
1.251     brouard  5491:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5492:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5493:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5494:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5495:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5496:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5497:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5498:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5499:   strcpy(fileresp,"P_");
                   5500:   strcat(fileresp,fileresu);
                   5501:   /*strcat(fileresphtm,fileresu);*/
                   5502:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5503:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5504:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5505:     exit(0);
                   5506:   }
1.240     brouard  5507:   
1.226     brouard  5508:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5509:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5510:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5511:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5512:     fflush(ficlog);
                   5513:     exit(70); 
                   5514:   }
                   5515:   else{
                   5516:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5517: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5518: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5519:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5520:   }
1.319     brouard  5521:   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  5522:   
1.226     brouard  5523:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5524:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5525:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5526:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5527:     fflush(ficlog);
                   5528:     exit(70); 
1.240     brouard  5529:   } else{
1.226     brouard  5530:     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  5531: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5532: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5533:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5534:   }
1.319     brouard  5535:   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  5536:   
1.253     brouard  5537:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5538:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5539:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5540:   j1=0;
1.126     brouard  5541:   
1.227     brouard  5542:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5543:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5544:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5545:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5546:   
                   5547:   
1.226     brouard  5548:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5549:      reference=low_education V1=0,V2=0
                   5550:      med_educ                V1=1 V2=0, 
                   5551:      high_educ               V1=0 V2=1
1.330     brouard  5552:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5553:   */
1.249     brouard  5554:   dateintsum=0;
                   5555:   k2cpt=0;
                   5556: 
1.253     brouard  5557:   if(cptcoveff == 0 )
1.265     brouard  5558:     nl=1;  /* Constant and age model only */
1.253     brouard  5559:   else
                   5560:     nl=2;
1.265     brouard  5561: 
                   5562:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5563:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5564:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5565:    *     freq[s1][s2][iage] =0.
                   5566:    *     Loop on iind
                   5567:    *       ++freq[s1][s2][iage] weighted
                   5568:    *     end iind
                   5569:    *     if covariate and j!0
                   5570:    *       headers Variable on one line
                   5571:    *     endif cov j!=0
                   5572:    *     header of frequency table by age
                   5573:    *     Loop on age
                   5574:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5575:    *       pos+=freq[s1][s2][iage] weighted
                   5576:    *       Loop on s1 initial state
                   5577:    *         fprintf(ficresp
                   5578:    *       end s1
                   5579:    *     end age
                   5580:    *     if j!=0 computes starting values
                   5581:    *     end compute starting values
                   5582:    *   end j1
                   5583:    * end nl 
                   5584:    */
1.253     brouard  5585:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5586:     if(nj==1)
                   5587:       j=0;  /* First pass for the constant */
1.265     brouard  5588:     else{
1.335     brouard  5589:       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  5590:     }
1.251     brouard  5591:     first=1;
1.332     brouard  5592:     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  5593:       posproptt=0.;
1.330     brouard  5594:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5595:        scanf("%d", i);*/
                   5596:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5597:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5598:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5599:            freq[i][s2][m]=0;
1.251     brouard  5600:       
                   5601:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5602:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5603:          prop[i][m]=0;
                   5604:        posprop[i]=0;
                   5605:        pospropt[i]=0;
                   5606:       }
1.283     brouard  5607:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5608:         idq[z1]=0.;
                   5609:         meanq[z1]=0.;
                   5610:         stdq[z1]=0.;
1.283     brouard  5611:       }
                   5612:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5613:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5614:       /*         meanqt[m][z1]=0.; */
                   5615:       /*       } */
                   5616:       /* }       */
1.251     brouard  5617:       /* dateintsum=0; */
                   5618:       /* k2cpt=0; */
                   5619:       
1.265     brouard  5620:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5621:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5622:        bool=1;
                   5623:        if(j !=0){
                   5624:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5625:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5626:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5627:                /* if(Tvaraff[z1] ==-20){ */
                   5628:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5629:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5630:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5631:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5632:                /* 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); */
                   5633:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5634:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5635:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5636:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5637:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5638:                  /* 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", */
                   5639:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5640:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5641:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5642:                } /* Onlyf fixed */
                   5643:              } /* end z1 */
1.335     brouard  5644:            } /* cptcoveff > 0 */
1.251     brouard  5645:          } /* end any */
                   5646:        }/* end j==0 */
1.265     brouard  5647:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5648:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5649:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5650:            m=mw[mi][iind];
                   5651:            if(j!=0){
                   5652:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5653:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5654:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5655:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5656:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5657:                    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  5658:                                                                                      value is -1, we don't select. It differs from the 
                   5659:                                                                                      constant and age model which counts them. */
                   5660:                      bool=0; /* not selected */
                   5661:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5662:                    /* i1=Tvaraff[z1]; */
                   5663:                    /* i2=TnsdVar[i1]; */
                   5664:                    /* i3=nbcode[i1][i2]; */
                   5665:                    /* i4=covar[i1][iind]; */
                   5666:                    /* if(i4 != i3){ */
                   5667:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5668:                      bool=0;
                   5669:                    }
                   5670:                  }
                   5671:                }
                   5672:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5673:            } /* end j==0 */
                   5674:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5675:            if(bool==1){ /*Selected */
1.251     brouard  5676:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5677:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5678:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5679:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5680:              if(m >=firstpass && m <=lastpass){
                   5681:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5682:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5683:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5684:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5685:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5686:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5687:                if (m<lastpass) {
                   5688:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5689:                  /*   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]); */
                   5690:                  if(s[m][iind]==-1)
                   5691:                    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.));
                   5692:                  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  5693:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5694:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5695:                      idq[z1]=idq[z1]+weight[iind];
                   5696:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5697:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5698:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5699:                    }
1.284     brouard  5700:                  }
1.251     brouard  5701:                  /* if((int)agev[m][iind] == 55) */
                   5702:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5703:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5704:                  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  5705:                }
1.251     brouard  5706:              } /* end if between passes */  
                   5707:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5708:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5709:                k2cpt++;
                   5710:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5711:              }
1.251     brouard  5712:            }else{
                   5713:              bool=1;
                   5714:            }/* end bool 2 */
                   5715:          } /* end m */
1.284     brouard  5716:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5717:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5718:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5719:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5720:          /* } */
1.251     brouard  5721:        } /* end bool */
                   5722:       } /* end iind = 1 to imx */
1.319     brouard  5723:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5724:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5725:       
                   5726:       
                   5727:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5728:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5729:         pstamp(ficresp);
1.335     brouard  5730:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5731:         pstamp(ficresp);
1.251     brouard  5732:        printf( "\n#********** Variable "); 
                   5733:        fprintf(ficresp, "\n#********** Variable "); 
                   5734:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5735:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5736:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5737:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5738:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5739:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5740:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5741:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5742:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5743:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5744:          }else{
1.330     brouard  5745:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5746:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5747:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5748:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5749:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5750:          }
                   5751:        }
                   5752:        printf( "**********\n#");
                   5753:        fprintf(ficresp, "**********\n#");
                   5754:        fprintf(ficresphtm, "**********</h3>\n");
                   5755:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5756:        fprintf(ficlog, "**********\n");
                   5757:       }
1.284     brouard  5758:       /*
                   5759:        Printing means of quantitative variables if any
                   5760:       */
                   5761:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5762:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5763:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5764:        if(weightopt==1){
                   5765:          printf(" Weighted mean and standard deviation of");
                   5766:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5767:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5768:        }
1.311     brouard  5769:        /* mu = \frac{w x}{\sum w}
                   5770:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5771:        */
                   5772:        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]));
                   5773:        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]));
                   5774:        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  5775:       }
                   5776:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5777:       /*       for(m=1;m<=lastpass;m++){ */
                   5778:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5779:       /*   } */
                   5780:       /* } */
1.283     brouard  5781: 
1.251     brouard  5782:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5783:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5784:         fprintf(ficresp, " Age");
1.335     brouard  5785:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5786:          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]]);
                   5787:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5788:        }
1.251     brouard  5789:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5790:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5791:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5792:       }
1.335     brouard  5793:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5794:       fprintf(ficresphtm, "\n");
                   5795:       
                   5796:       /* Header of frequency table by age */
                   5797:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5798:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5799:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5800:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5801:          if(s2!=0 && m!=0)
                   5802:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5803:        }
1.226     brouard  5804:       }
1.251     brouard  5805:       fprintf(ficresphtmfr, "\n");
                   5806:     
                   5807:       /* For each age */
                   5808:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5809:        fprintf(ficresphtm,"<tr>");
                   5810:        if(iage==iagemax+1){
                   5811:          fprintf(ficlog,"1");
                   5812:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5813:        }else if(iage==iagemax+2){
                   5814:          fprintf(ficlog,"0");
                   5815:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5816:        }else if(iage==iagemax+3){
                   5817:          fprintf(ficlog,"Total");
                   5818:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5819:        }else{
1.240     brouard  5820:          if(first==1){
1.251     brouard  5821:            first=0;
                   5822:            printf("See log file for details...\n");
                   5823:          }
                   5824:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5825:          fprintf(ficlog,"Age %d", iage);
                   5826:        }
1.265     brouard  5827:        for(s1=1; s1 <=nlstate ; s1++){
                   5828:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5829:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5830:        }
1.265     brouard  5831:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5832:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5833:            pos += freq[s1][m][iage];
                   5834:          if(pp[s1]>=1.e-10){
1.251     brouard  5835:            if(first==1){
1.265     brouard  5836:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5837:            }
1.265     brouard  5838:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5839:          }else{
                   5840:            if(first==1)
1.265     brouard  5841:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5842:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5843:          }
                   5844:        }
                   5845:       
1.265     brouard  5846:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5847:          /* posprop[s1]=0; */
                   5848:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5849:            pp[s1] += freq[s1][m][iage];
                   5850:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5851:       
                   5852:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5853:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5854:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5855:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5856:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5857:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5858:        }
                   5859:        
                   5860:        /* Writing ficresp */
1.335     brouard  5861:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5862:           if( iage <= iagemax){
                   5863:            fprintf(ficresp," %d",iage);
                   5864:           }
                   5865:         }else if( nj==2){
                   5866:           if( iage <= iagemax){
                   5867:            fprintf(ficresp," %d",iage);
1.335     brouard  5868:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5869:           }
1.240     brouard  5870:        }
1.265     brouard  5871:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5872:          if(pos>=1.e-5){
1.251     brouard  5873:            if(first==1)
1.265     brouard  5874:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5875:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5876:          }else{
                   5877:            if(first==1)
1.265     brouard  5878:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5879:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5880:          }
                   5881:          if( iage <= iagemax){
                   5882:            if(pos>=1.e-5){
1.335     brouard  5883:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5884:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5885:               }else if( nj==2){
                   5886:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5887:               }
                   5888:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5889:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5890:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5891:            } else{
1.335     brouard  5892:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5893:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5894:            }
1.240     brouard  5895:          }
1.265     brouard  5896:          pospropt[s1] +=posprop[s1];
                   5897:        } /* end loop s1 */
1.251     brouard  5898:        /* pospropt=0.; */
1.265     brouard  5899:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5900:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5901:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5902:              if(first==1){
1.265     brouard  5903:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5904:              }
1.265     brouard  5905:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5906:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5907:            }
1.265     brouard  5908:            if(s1!=0 && m!=0)
                   5909:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5910:          }
1.265     brouard  5911:        } /* end loop s1 */
1.251     brouard  5912:        posproptt=0.; 
1.265     brouard  5913:        for(s1=1; s1 <=nlstate; s1++){
                   5914:          posproptt += pospropt[s1];
1.251     brouard  5915:        }
                   5916:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5917:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5918:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5919:          if(iage <= iagemax)
                   5920:            fprintf(ficresp,"\n");
1.240     brouard  5921:        }
1.251     brouard  5922:        if(first==1)
                   5923:          printf("Others in log...\n");
                   5924:        fprintf(ficlog,"\n");
                   5925:       } /* end loop age iage */
1.265     brouard  5926:       
1.251     brouard  5927:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5928:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5929:        if(posproptt < 1.e-5){
1.265     brouard  5930:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5931:        }else{
1.265     brouard  5932:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5933:        }
1.226     brouard  5934:       }
1.251     brouard  5935:       fprintf(ficresphtm,"</tr>\n");
                   5936:       fprintf(ficresphtm,"</table>\n");
                   5937:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5938:       if(posproptt < 1.e-5){
1.251     brouard  5939:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5940:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5941:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5942:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5943:        invalidvarcomb[j1]=1;
1.226     brouard  5944:       }else{
1.338     brouard  5945:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5946:        invalidvarcomb[j1]=0;
1.226     brouard  5947:       }
1.251     brouard  5948:       fprintf(ficresphtmfr,"</table>\n");
                   5949:       fprintf(ficlog,"\n");
                   5950:       if(j!=0){
                   5951:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5952:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5953:          for(k=1; k <=(nlstate+ndeath); k++){
                   5954:            if (k != i) {
1.265     brouard  5955:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5956:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5957:                  if(j1==1){ /* All dummy covariates to zero */
                   5958:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5959:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5960:                    printf("%d%d ",i,k);
                   5961:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5962:                    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]));
                   5963:                    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]));
                   5964:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5965:                  }
1.253     brouard  5966:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5967:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5968:                    x[iage]= (double)iage;
                   5969:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5970:                    /* 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  5971:                  }
1.268     brouard  5972:                  /* Some are not finite, but linreg will ignore these ages */
                   5973:                  no=0;
1.253     brouard  5974:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5975:                  pstart[s1]=b;
                   5976:                  pstart[s1-1]=a;
1.252     brouard  5977:                }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 */ 
                   5978:                  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]);
                   5979:                  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  5980:                  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  5981:                  printf("%d%d ",i,k);
                   5982:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5983:                  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  5984:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5985:                  ;
                   5986:                }
                   5987:                /* printf("%12.7f )", param[i][jj][k]); */
                   5988:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5989:                s1++; 
1.251     brouard  5990:              } /* end jj */
                   5991:            } /* end k!= i */
                   5992:          } /* end k */
1.265     brouard  5993:        } /* end i, s1 */
1.251     brouard  5994:       } /* end j !=0 */
                   5995:     } /* end selected combination of covariate j1 */
                   5996:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5997:       printf("#Freqsummary: Starting values for the constants:\n");
                   5998:       fprintf(ficlog,"\n");
1.265     brouard  5999:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  6000:        for(k=1; k <=(nlstate+ndeath); k++){
                   6001:          if (k != i) {
                   6002:            printf("%d%d ",i,k);
                   6003:            fprintf(ficlog,"%d%d ",i,k);
                   6004:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  6005:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  6006:              if(jj==1){ /* Age has to be done */
1.265     brouard  6007:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6008:                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]));
                   6009:                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  6010:              }
                   6011:              /* printf("%12.7f )", param[i][jj][k]); */
                   6012:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  6013:              s1++; 
1.250     brouard  6014:            }
1.251     brouard  6015:            printf("\n");
                   6016:            fprintf(ficlog,"\n");
1.250     brouard  6017:          }
                   6018:        }
1.284     brouard  6019:       } /* end of state i */
1.251     brouard  6020:       printf("#Freqsummary\n");
                   6021:       fprintf(ficlog,"\n");
1.265     brouard  6022:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6023:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6024:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6025:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6026:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6027:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6028:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6029:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  6030:          /* } */
                   6031:        }
1.265     brouard  6032:       } /* end loop s1 */
1.251     brouard  6033:       
                   6034:       printf("\n");
                   6035:       fprintf(ficlog,"\n");
                   6036:     } /* end j=0 */
1.249     brouard  6037:   } /* end j */
1.252     brouard  6038: 
1.253     brouard  6039:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6040:     for(i=1, jk=1; i <=nlstate; i++){
                   6041:       for(j=1; j <=nlstate+ndeath; j++){
                   6042:        if(j!=i){
                   6043:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6044:          printf("%1d%1d",i,j);
                   6045:          fprintf(ficparo,"%1d%1d",i,j);
                   6046:          for(k=1; k<=ncovmodel;k++){
                   6047:            /*    printf(" %lf",param[i][j][k]); */
                   6048:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6049:            p[jk]=pstart[jk];
                   6050:            printf(" %f ",pstart[jk]);
                   6051:            fprintf(ficparo," %f ",pstart[jk]);
                   6052:            jk++;
                   6053:          }
                   6054:          printf("\n");
                   6055:          fprintf(ficparo,"\n");
                   6056:        }
                   6057:       }
                   6058:     }
                   6059:   } /* end mle=-2 */
1.226     brouard  6060:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6061:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6062:   
1.226     brouard  6063:   fclose(ficresp);
                   6064:   fclose(ficresphtm);
                   6065:   fclose(ficresphtmfr);
1.283     brouard  6066:   free_vector(idq,1,nqfveff);
1.226     brouard  6067:   free_vector(meanq,1,nqfveff);
1.284     brouard  6068:   free_vector(stdq,1,nqfveff);
1.226     brouard  6069:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6070:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6071:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6072:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6073:   free_vector(pospropt,1,nlstate);
                   6074:   free_vector(posprop,1,nlstate);
1.251     brouard  6075:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6076:   free_vector(pp,1,nlstate);
                   6077:   /* End of freqsummary */
                   6078: }
1.126     brouard  6079: 
1.268     brouard  6080: /* Simple linear regression */
                   6081: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6082: 
                   6083:   /* y=a+bx regression */
                   6084:   double   sumx = 0.0;                        /* sum of x                      */
                   6085:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6086:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6087:   double   sumy = 0.0;                        /* sum of y                      */
                   6088:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6089:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6090:   double yhat;
                   6091:   
                   6092:   double denom=0;
                   6093:   int i;
                   6094:   int ne=*no;
                   6095:   
                   6096:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6097:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6098:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6099:       continue;
                   6100:     }
                   6101:     ne=ne+1;
                   6102:     sumx  += x[i];       
                   6103:     sumx2 += x[i]*x[i];  
                   6104:     sumxy += x[i] * y[i];
                   6105:     sumy  += y[i];      
                   6106:     sumy2 += y[i]*y[i]; 
                   6107:     denom = (ne * sumx2 - sumx*sumx);
                   6108:     /* 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); */
                   6109:   } 
                   6110:   
                   6111:   denom = (ne * sumx2 - sumx*sumx);
                   6112:   if (denom == 0) {
                   6113:     // vertical, slope m is infinity
                   6114:     *b = INFINITY;
                   6115:     *a = 0;
                   6116:     if (r) *r = 0;
                   6117:     return 1;
                   6118:   }
                   6119:   
                   6120:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6121:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6122:   if (r!=NULL) {
                   6123:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6124:       sqrt((sumx2 - sumx*sumx/ne) *
                   6125:           (sumy2 - sumy*sumy/ne));
                   6126:   }
                   6127:   *no=ne;
                   6128:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6129:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6130:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6131:       continue;
                   6132:     }
                   6133:     ne=ne+1;
                   6134:     yhat = y[i] - *a -*b* x[i];
                   6135:     sume2  += yhat * yhat ;       
                   6136:     
                   6137:     denom = (ne * sumx2 - sumx*sumx);
                   6138:     /* 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); */
                   6139:   } 
                   6140:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6141:   *sa= *sb * sqrt(sumx2/ne);
                   6142:   
                   6143:   return 0; 
                   6144: }
                   6145: 
1.126     brouard  6146: /************ Prevalence ********************/
1.227     brouard  6147: 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)
                   6148: {  
                   6149:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6150:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6151:      We still use firstpass and lastpass as another selection.
                   6152:   */
1.126     brouard  6153:  
1.227     brouard  6154:   int i, m, jk, j1, bool, z1,j, iv;
                   6155:   int mi; /* Effective wave */
                   6156:   int iage;
                   6157:   double agebegin, ageend;
                   6158: 
                   6159:   double **prop;
                   6160:   double posprop; 
                   6161:   double  y2; /* in fractional years */
                   6162:   int iagemin, iagemax;
                   6163:   int first; /** to stop verbosity which is redirected to log file */
                   6164: 
                   6165:   iagemin= (int) agemin;
                   6166:   iagemax= (int) agemax;
                   6167:   /*pp=vector(1,nlstate);*/
1.251     brouard  6168:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6169:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6170:   j1=0;
1.222     brouard  6171:   
1.227     brouard  6172:   /*j=cptcoveff;*/
                   6173:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6174:   
1.288     brouard  6175:   first=0;
1.335     brouard  6176:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6177:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6178:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6179:        prop[i][iage]=0.0;
                   6180:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6181:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6182:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6183:     
                   6184:     for (i=1; i<=imx; i++) { /* Each individual */
                   6185:       bool=1;
                   6186:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6187:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6188:        m=mw[mi][i];
                   6189:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6190:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6191:        for (z1=1; z1<=cptcoveff; z1++){
                   6192:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6193:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6194:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6195:              bool=0;
                   6196:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6197:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6198:              bool=0;
                   6199:            }
                   6200:        }
                   6201:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6202:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6203:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6204:          if(m >=firstpass && m <=lastpass){
                   6205:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6206:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6207:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6208:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6209:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6210:                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); 
                   6211:                exit(1);
                   6212:              }
                   6213:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6214:                /*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]]);*/
                   6215:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6216:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6217:              } /* end valid statuses */ 
                   6218:            } /* end selection of dates */
                   6219:          } /* end selection of waves */
                   6220:        } /* end bool */
                   6221:       } /* end wave */
                   6222:     } /* end individual */
                   6223:     for(i=iagemin; i <= iagemax+3; i++){  
                   6224:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6225:        posprop += prop[jk][i]; 
                   6226:       } 
                   6227:       
                   6228:       for(jk=1; jk <=nlstate ; jk++){      
                   6229:        if( i <=  iagemax){ 
                   6230:          if(posprop>=1.e-5){ 
                   6231:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6232:          } else{
1.288     brouard  6233:            if(!first){
                   6234:              first=1;
1.266     brouard  6235:              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]);
                   6236:            }else{
1.288     brouard  6237:              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  6238:            }
                   6239:          }
                   6240:        } 
                   6241:       }/* end jk */ 
                   6242:     }/* end i */ 
1.222     brouard  6243:      /*} *//* end i1 */
1.227     brouard  6244:   } /* end j1 */
1.222     brouard  6245:   
1.227     brouard  6246:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6247:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6248:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6249: }  /* End of prevalence */
1.126     brouard  6250: 
                   6251: /************* Waves Concatenation ***************/
                   6252: 
                   6253: 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)
                   6254: {
1.298     brouard  6255:   /* 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  6256:      Death is a valid wave (if date is known).
                   6257:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6258:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6259:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6260:   */
1.126     brouard  6261: 
1.224     brouard  6262:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6263:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6264:      double sum=0., jmean=0.;*/
1.224     brouard  6265:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6266:   int j, k=0,jk, ju, jl;
                   6267:   double sum=0.;
                   6268:   first=0;
1.214     brouard  6269:   firstwo=0;
1.217     brouard  6270:   firsthree=0;
1.218     brouard  6271:   firstfour=0;
1.164     brouard  6272:   jmin=100000;
1.126     brouard  6273:   jmax=-1;
                   6274:   jmean=0.;
1.224     brouard  6275: 
                   6276: /* Treating live states */
1.214     brouard  6277:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6278:     mi=0;  /* First valid wave */
1.227     brouard  6279:     mli=0; /* Last valid wave */
1.309     brouard  6280:     m=firstpass;  /* Loop on waves */
                   6281:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6282:       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 */
                   6283:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6284:       }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  6285:        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  6286:        mli=m;
1.224     brouard  6287:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6288:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6289:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6290:       }
1.309     brouard  6291:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6292: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6293:        break;
1.224     brouard  6294: #else
1.317     brouard  6295:        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  6296:          if(firsthree == 0){
1.302     brouard  6297:            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  6298:            firsthree=1;
1.317     brouard  6299:          }else if(firsthree >=1 && firsthree < 10){
                   6300:            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);
                   6301:            firsthree++;
                   6302:          }else if(firsthree == 10){
                   6303:            printf("Information, too many Information flags: no more reported to log either\n");
                   6304:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6305:            firsthree++;
                   6306:          }else{
                   6307:            firsthree++;
1.227     brouard  6308:          }
1.309     brouard  6309:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6310:          mli=m;
                   6311:        }
                   6312:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6313:          nbwarn++;
1.309     brouard  6314:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6315:            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);
                   6316:            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);
                   6317:          }
                   6318:          break;
                   6319:        }
                   6320:        break;
1.224     brouard  6321: #endif
1.227     brouard  6322:       }/* End m >= lastpass */
1.126     brouard  6323:     }/* end while */
1.224     brouard  6324: 
1.227     brouard  6325:     /* 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  6326:     /* After last pass */
1.224     brouard  6327: /* Treating death states */
1.214     brouard  6328:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6329:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6330:       /* } */
1.126     brouard  6331:       mi++;    /* Death is another wave */
                   6332:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6333:       /* Only death is a correct wave */
1.126     brouard  6334:       mw[mi][i]=m;
1.257     brouard  6335:     } /* else not in a death state */
1.224     brouard  6336: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6337:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6338:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6339:        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  6340:          nbwarn++;
                   6341:          if(firstfiv==0){
1.309     brouard  6342:            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  6343:            firstfiv=1;
                   6344:          }else{
1.309     brouard  6345:            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  6346:          }
1.309     brouard  6347:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6348:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6349:          nberr++;
                   6350:          if(firstwo==0){
1.309     brouard  6351:            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  6352:            firstwo=1;
                   6353:          }
1.309     brouard  6354:          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  6355:        }
1.257     brouard  6356:       }else{ /* if date of interview is unknown */
1.227     brouard  6357:        /* death is known but not confirmed by death status at any wave */
                   6358:        if(firstfour==0){
1.309     brouard  6359:          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  6360:          firstfour=1;
                   6361:        }
1.309     brouard  6362:        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  6363:       }
1.224     brouard  6364:     } /* end if date of death is known */
                   6365: #endif
1.309     brouard  6366:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6367:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6368:     if(mi==0){
                   6369:       nbwarn++;
                   6370:       if(first==0){
1.227     brouard  6371:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6372:        first=1;
1.126     brouard  6373:       }
                   6374:       if(first==1){
1.227     brouard  6375:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6376:       }
                   6377:     } /* end mi==0 */
                   6378:   } /* End individuals */
1.214     brouard  6379:   /* wav and mw are no more changed */
1.223     brouard  6380:        
1.317     brouard  6381:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6382:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6383: 
                   6384: 
1.126     brouard  6385:   for(i=1; i<=imx; i++){
                   6386:     for(mi=1; mi<wav[i];mi++){
                   6387:       if (stepm <=0)
1.227     brouard  6388:        dh[mi][i]=1;
1.126     brouard  6389:       else{
1.260     brouard  6390:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6391:          if (agedc[i] < 2*AGESUP) {
                   6392:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6393:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6394:            else if(j<0){
                   6395:              nberr++;
                   6396:              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]);
                   6397:              j=1; /* Temporary Dangerous patch */
                   6398:              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);
                   6399:              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]);
                   6400:              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);
                   6401:            }
                   6402:            k=k+1;
                   6403:            if (j >= jmax){
                   6404:              jmax=j;
                   6405:              ijmax=i;
                   6406:            }
                   6407:            if (j <= jmin){
                   6408:              jmin=j;
                   6409:              ijmin=i;
                   6410:            }
                   6411:            sum=sum+j;
                   6412:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6413:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6414:          }
                   6415:        }
                   6416:        else{
                   6417:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6418: /*       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  6419:                                        
1.227     brouard  6420:          k=k+1;
                   6421:          if (j >= jmax) {
                   6422:            jmax=j;
                   6423:            ijmax=i;
                   6424:          }
                   6425:          else if (j <= jmin){
                   6426:            jmin=j;
                   6427:            ijmin=i;
                   6428:          }
                   6429:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6430:          /*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]);*/
                   6431:          if(j<0){
                   6432:            nberr++;
                   6433:            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]);
                   6434:            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]);
                   6435:          }
                   6436:          sum=sum+j;
                   6437:        }
                   6438:        jk= j/stepm;
                   6439:        jl= j -jk*stepm;
                   6440:        ju= j -(jk+1)*stepm;
                   6441:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6442:          if(jl==0){
                   6443:            dh[mi][i]=jk;
                   6444:            bh[mi][i]=0;
                   6445:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6446:                  * to avoid the price of an extra matrix product in likelihood */
                   6447:            dh[mi][i]=jk+1;
                   6448:            bh[mi][i]=ju;
                   6449:          }
                   6450:        }else{
                   6451:          if(jl <= -ju){
                   6452:            dh[mi][i]=jk;
                   6453:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6454:                                 * is higher than the multiple of stepm and negative otherwise.
                   6455:                                 */
                   6456:          }
                   6457:          else{
                   6458:            dh[mi][i]=jk+1;
                   6459:            bh[mi][i]=ju;
                   6460:          }
                   6461:          if(dh[mi][i]==0){
                   6462:            dh[mi][i]=1; /* At least one step */
                   6463:            bh[mi][i]=ju; /* At least one step */
                   6464:            /*  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);*/
                   6465:          }
                   6466:        } /* end if mle */
1.126     brouard  6467:       }
                   6468:     } /* end wave */
                   6469:   }
                   6470:   jmean=sum/k;
                   6471:   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  6472:   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  6473: }
1.126     brouard  6474: 
                   6475: /*********** Tricode ****************************/
1.220     brouard  6476:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6477:  {
                   6478:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6479:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6480:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6481:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6482:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6483:     */
1.130     brouard  6484: 
1.242     brouard  6485:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6486:    int modmaxcovj=0; /* Modality max of covariates j */
                   6487:    int cptcode=0; /* Modality max of covariates j */
                   6488:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6489: 
                   6490: 
1.242     brouard  6491:    /* cptcoveff=0;  */
                   6492:    /* *cptcov=0; */
1.126     brouard  6493:  
1.242     brouard  6494:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6495:    for (k=1; k <= maxncov; k++)
                   6496:      for(j=1; j<=2; j++)
                   6497:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6498: 
1.242     brouard  6499:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6500:    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  6501:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6502:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6503:      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  6504:        switch(Fixed[k]) {
                   6505:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6506:         modmaxcovj=0;
                   6507:         modmincovj=0;
1.242     brouard  6508:         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  6509:           /* 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  6510:           ij=(int)(covar[Tvar[k]][i]);
                   6511:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6512:            * If product of Vn*Vm, still boolean *:
                   6513:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6514:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6515:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6516:              modality of the nth covariate of individual i. */
                   6517:           if (ij > modmaxcovj)
                   6518:             modmaxcovj=ij; 
                   6519:           else if (ij < modmincovj) 
                   6520:             modmincovj=ij; 
1.287     brouard  6521:           if (ij <0 || ij >1 ){
1.311     brouard  6522:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6523:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6524:             fflush(ficlog);
                   6525:             exit(1);
1.287     brouard  6526:           }
                   6527:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6528:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6529:             exit(1);
                   6530:           }else
                   6531:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6532:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6533:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6534:           /* getting the maximum value of the modality of the covariate
                   6535:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6536:              female ies 1, then modmaxcovj=1.
                   6537:           */
                   6538:         } /* end for loop on individuals i */
                   6539:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6540:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6541:         cptcode=modmaxcovj;
                   6542:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6543:         /*for (i=0; i<=cptcode; i++) {*/
                   6544:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6545:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6546:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6547:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6548:             if( j != -1){
                   6549:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6550:                                  covariate for which somebody answered excluding 
                   6551:                                  undefined. Usually 2: 0 and 1. */
                   6552:             }
                   6553:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6554:                                     covariate for which somebody answered including 
                   6555:                                     undefined. Usually 3: -1, 0 and 1. */
                   6556:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6557:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6558:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6559:                        
1.242     brouard  6560:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6561:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6562:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6563:         /* modmincovj=3; modmaxcovj = 7; */
                   6564:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6565:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6566:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6567:         /* nbcode[Tvar[j]][ij]=k; */
                   6568:         /* nbcode[Tvar[j]][1]=0; */
                   6569:         /* nbcode[Tvar[j]][2]=1; */
                   6570:         /* nbcode[Tvar[j]][3]=2; */
                   6571:         /* To be continued (not working yet). */
                   6572:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6573: 
                   6574:         /* 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*/
                   6575:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6576:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6577:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6578:         /*, could be restored in the future */
                   6579:         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  6580:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6581:             break;
                   6582:           }
                   6583:           ij++;
1.287     brouard  6584:           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  6585:           cptcode = ij; /* New max modality for covar j */
                   6586:         } /* end of loop on modality i=-1 to 1 or more */
                   6587:         break;
                   6588:        case 1: /* Testing on varying covariate, could be simple and
                   6589:                * should look at waves or product of fixed *
                   6590:                * varying. No time to test -1, assuming 0 and 1 only */
                   6591:         ij=0;
                   6592:         for(i=0; i<=1;i++){
                   6593:           nbcode[Tvar[k]][++ij]=i;
                   6594:         }
                   6595:         break;
                   6596:        default:
                   6597:         break;
                   6598:        } /* end switch */
                   6599:      } /* end dummy test */
1.349     brouard  6600:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6601:        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  6602:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6603:           printf("Error k=%d \n",k);
                   6604:           exit(1);
                   6605:         }
1.311     brouard  6606:         if(isnan(covar[Tvar[k]][i])){
                   6607:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6608:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6609:           fflush(ficlog);
                   6610:           exit(1);
                   6611:          }
                   6612:        }
1.335     brouard  6613:      } /* end Quanti */
1.287     brouard  6614:    } /* 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  6615:   
                   6616:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6617:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6618:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6619:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6620:      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 */ 
                   6621:      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 */
                   6622:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6623:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6624:   
                   6625:    ij=0;
                   6626:    /* 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  6627:    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 */
                   6628:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6629:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6630:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6631:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6632:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6633:        /* 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  6634:        /* If product not in single variable we don't print results */
                   6635:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6636:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6637:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6638:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6639:        /* ij            1    2                                            3  */  
                   6640:        /* Tvaraff[ij]=  4    3                                            1  */
                   6641:        /* Tmodelind[ij]=2    3                                            9  */
                   6642:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6643:        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*/
                   6644:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6645:        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 */
                   6646:        if(Fixed[k]!=0)
                   6647:         anyvaryingduminmodel=1;
                   6648:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6649:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6650:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6651:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6652:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6653:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6654:      } 
                   6655:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6656:    /* ij--; */
                   6657:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6658:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6659:                * because they can be excluded from the model and real
                   6660:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6661:    for(j=ij+1; j<= cptcovt; j++){
                   6662:      Tvaraff[j]=0;
                   6663:      Tmodelind[j]=0;
                   6664:    }
                   6665:    for(j=ntveff+1; j<= cptcovt; j++){
                   6666:      TmodelInvind[j]=0;
                   6667:    }
                   6668:    /* To be sorted */
                   6669:    ;
                   6670:  }
1.126     brouard  6671: 
1.145     brouard  6672: 
1.126     brouard  6673: /*********** Health Expectancies ****************/
                   6674: 
1.235     brouard  6675:  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  6676: 
                   6677: {
                   6678:   /* Health expectancies, no variances */
1.329     brouard  6679:   /* cij is the combination in the list of combination of dummy covariates */
                   6680:   /* strstart is a string of time at start of computing */
1.164     brouard  6681:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6682:   int nhstepma, nstepma; /* Decreasing with age */
                   6683:   double age, agelim, hf;
                   6684:   double ***p3mat;
                   6685:   double eip;
                   6686: 
1.238     brouard  6687:   /* pstamp(ficreseij); */
1.126     brouard  6688:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6689:   fprintf(ficreseij,"# Age");
                   6690:   for(i=1; i<=nlstate;i++){
                   6691:     for(j=1; j<=nlstate;j++){
                   6692:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6693:     }
                   6694:     fprintf(ficreseij," e%1d. ",i);
                   6695:   }
                   6696:   fprintf(ficreseij,"\n");
                   6697: 
                   6698:   
                   6699:   if(estepm < stepm){
                   6700:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6701:   }
                   6702:   else  hstepm=estepm;   
                   6703:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6704:    * This is mainly to measure the difference between two models: for example
                   6705:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6706:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6707:    * progression in between and thus overestimating or underestimating according
                   6708:    * to the curvature of the survival function. If, for the same date, we 
                   6709:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6710:    * to compare the new estimate of Life expectancy with the same linear 
                   6711:    * hypothesis. A more precise result, taking into account a more precise
                   6712:    * curvature will be obtained if estepm is as small as stepm. */
                   6713: 
                   6714:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6715:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6716:      nhstepm is the number of hstepm from age to agelim 
                   6717:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6718:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6719:      and note for a fixed period like estepm months */
                   6720:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6721:      survival function given by stepm (the optimization length). Unfortunately it
                   6722:      means that if the survival funtion is printed only each two years of age and if
                   6723:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6724:      results. So we changed our mind and took the option of the best precision.
                   6725:   */
                   6726:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6727: 
                   6728:   agelim=AGESUP;
                   6729:   /* If stepm=6 months */
                   6730:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6731:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6732:     
                   6733: /* nhstepm age range expressed in number of stepm */
                   6734:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6735:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6736:   /* if (stepm >= YEARM) hstepm=1;*/
                   6737:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6738:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6739: 
                   6740:   for (age=bage; age<=fage; age ++){ 
                   6741:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6742:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6743:     /* if (stepm >= YEARM) hstepm=1;*/
                   6744:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6745: 
                   6746:     /* If stepm=6 months */
                   6747:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6748:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6749:     /* 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  6750:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6751:     
                   6752:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6753:     
                   6754:     printf("%d|",(int)age);fflush(stdout);
                   6755:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6756:     
                   6757:     /* Computing expectancies */
                   6758:     for(i=1; i<=nlstate;i++)
                   6759:       for(j=1; j<=nlstate;j++)
                   6760:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6761:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6762:          
                   6763:          /* 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]);*/
                   6764: 
                   6765:        }
                   6766: 
                   6767:     fprintf(ficreseij,"%3.0f",age );
                   6768:     for(i=1; i<=nlstate;i++){
                   6769:       eip=0;
                   6770:       for(j=1; j<=nlstate;j++){
                   6771:        eip +=eij[i][j][(int)age];
                   6772:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6773:       }
                   6774:       fprintf(ficreseij,"%9.4f", eip );
                   6775:     }
                   6776:     fprintf(ficreseij,"\n");
                   6777:     
                   6778:   }
                   6779:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6780:   printf("\n");
                   6781:   fprintf(ficlog,"\n");
                   6782:   
                   6783: }
                   6784: 
1.235     brouard  6785:  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  6786: 
                   6787: {
                   6788:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6789:      to initial status i, ei. .
1.126     brouard  6790:   */
1.336     brouard  6791:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6792:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6793:   int nhstepma, nstepma; /* Decreasing with age */
                   6794:   double age, agelim, hf;
                   6795:   double ***p3matp, ***p3matm, ***varhe;
                   6796:   double **dnewm,**doldm;
                   6797:   double *xp, *xm;
                   6798:   double **gp, **gm;
                   6799:   double ***gradg, ***trgradg;
                   6800:   int theta;
                   6801: 
                   6802:   double eip, vip;
                   6803: 
                   6804:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6805:   xp=vector(1,npar);
                   6806:   xm=vector(1,npar);
                   6807:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6808:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6809:   
                   6810:   pstamp(ficresstdeij);
                   6811:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6812:   fprintf(ficresstdeij,"# Age");
                   6813:   for(i=1; i<=nlstate;i++){
                   6814:     for(j=1; j<=nlstate;j++)
                   6815:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6816:     fprintf(ficresstdeij," e%1d. ",i);
                   6817:   }
                   6818:   fprintf(ficresstdeij,"\n");
                   6819: 
                   6820:   pstamp(ficrescveij);
                   6821:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6822:   fprintf(ficrescveij,"# Age");
                   6823:   for(i=1; i<=nlstate;i++)
                   6824:     for(j=1; j<=nlstate;j++){
                   6825:       cptj= (j-1)*nlstate+i;
                   6826:       for(i2=1; i2<=nlstate;i2++)
                   6827:        for(j2=1; j2<=nlstate;j2++){
                   6828:          cptj2= (j2-1)*nlstate+i2;
                   6829:          if(cptj2 <= cptj)
                   6830:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6831:        }
                   6832:     }
                   6833:   fprintf(ficrescveij,"\n");
                   6834:   
                   6835:   if(estepm < stepm){
                   6836:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6837:   }
                   6838:   else  hstepm=estepm;   
                   6839:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6840:    * This is mainly to measure the difference between two models: for example
                   6841:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6842:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6843:    * progression in between and thus overestimating or underestimating according
                   6844:    * to the curvature of the survival function. If, for the same date, we 
                   6845:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6846:    * to compare the new estimate of Life expectancy with the same linear 
                   6847:    * hypothesis. A more precise result, taking into account a more precise
                   6848:    * curvature will be obtained if estepm is as small as stepm. */
                   6849: 
                   6850:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6851:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6852:      nhstepm is the number of hstepm from age to agelim 
                   6853:      nstepm is the number of stepm from age to agelin. 
                   6854:      Look at hpijx to understand the reason of that which relies in memory size
                   6855:      and note for a fixed period like estepm months */
                   6856:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6857:      survival function given by stepm (the optimization length). Unfortunately it
                   6858:      means that if the survival funtion is printed only each two years of age and if
                   6859:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6860:      results. So we changed our mind and took the option of the best precision.
                   6861:   */
                   6862:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6863: 
                   6864:   /* If stepm=6 months */
                   6865:   /* nhstepm age range expressed in number of stepm */
                   6866:   agelim=AGESUP;
                   6867:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6868:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6869:   /* if (stepm >= YEARM) hstepm=1;*/
                   6870:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6871:   
                   6872:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6873:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6874:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6875:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6876:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6877:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6878: 
                   6879:   for (age=bage; age<=fage; age ++){ 
                   6880:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6881:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6882:     /* if (stepm >= YEARM) hstepm=1;*/
                   6883:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6884:                
1.126     brouard  6885:     /* If stepm=6 months */
                   6886:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6887:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6888:     
                   6889:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6890:                
1.126     brouard  6891:     /* Computing  Variances of health expectancies */
                   6892:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6893:        decrease memory allocation */
                   6894:     for(theta=1; theta <=npar; theta++){
                   6895:       for(i=1; i<=npar; i++){ 
1.222     brouard  6896:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6897:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6898:       }
1.235     brouard  6899:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6900:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6901:                        
1.126     brouard  6902:       for(j=1; j<= nlstate; j++){
1.222     brouard  6903:        for(i=1; i<=nlstate; i++){
                   6904:          for(h=0; h<=nhstepm-1; h++){
                   6905:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6906:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6907:          }
                   6908:        }
1.126     brouard  6909:       }
1.218     brouard  6910:                        
1.126     brouard  6911:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6912:        for(h=0; h<=nhstepm-1; h++){
                   6913:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6914:        }
1.126     brouard  6915:     }/* End theta */
                   6916:     
                   6917:     
                   6918:     for(h=0; h<=nhstepm-1; h++)
                   6919:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6920:        for(theta=1; theta <=npar; theta++)
                   6921:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6922:     
1.218     brouard  6923:                
1.222     brouard  6924:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6925:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6926:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6927:                
1.222     brouard  6928:     printf("%d|",(int)age);fflush(stdout);
                   6929:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6930:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6931:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6932:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6933:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6934:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6935:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6936:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6937:       }
                   6938:     }
1.320     brouard  6939:     /* if((int)age ==50){ */
                   6940:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6941:     /* } */
1.126     brouard  6942:     /* Computing expectancies */
1.235     brouard  6943:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6944:     for(i=1; i<=nlstate;i++)
                   6945:       for(j=1; j<=nlstate;j++)
1.222     brouard  6946:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6947:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6948:                                        
1.222     brouard  6949:          /* 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  6950:                                        
1.222     brouard  6951:        }
1.269     brouard  6952: 
                   6953:     /* Standard deviation of expectancies ij */                
1.126     brouard  6954:     fprintf(ficresstdeij,"%3.0f",age );
                   6955:     for(i=1; i<=nlstate;i++){
                   6956:       eip=0.;
                   6957:       vip=0.;
                   6958:       for(j=1; j<=nlstate;j++){
1.222     brouard  6959:        eip += eij[i][j][(int)age];
                   6960:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6961:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6962:        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  6963:       }
                   6964:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6965:     }
                   6966:     fprintf(ficresstdeij,"\n");
1.218     brouard  6967:                
1.269     brouard  6968:     /* Variance of expectancies ij */          
1.126     brouard  6969:     fprintf(ficrescveij,"%3.0f",age );
                   6970:     for(i=1; i<=nlstate;i++)
                   6971:       for(j=1; j<=nlstate;j++){
1.222     brouard  6972:        cptj= (j-1)*nlstate+i;
                   6973:        for(i2=1; i2<=nlstate;i2++)
                   6974:          for(j2=1; j2<=nlstate;j2++){
                   6975:            cptj2= (j2-1)*nlstate+i2;
                   6976:            if(cptj2 <= cptj)
                   6977:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6978:          }
1.126     brouard  6979:       }
                   6980:     fprintf(ficrescveij,"\n");
1.218     brouard  6981:                
1.126     brouard  6982:   }
                   6983:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6984:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6985:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6986:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6987:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6988:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6989:   printf("\n");
                   6990:   fprintf(ficlog,"\n");
1.218     brouard  6991:        
1.126     brouard  6992:   free_vector(xm,1,npar);
                   6993:   free_vector(xp,1,npar);
                   6994:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6995:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6996:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6997: }
1.218     brouard  6998:  
1.126     brouard  6999: /************ Variance ******************/
1.235     brouard  7000:  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  7001:  {
1.279     brouard  7002:    /** Variance of health expectancies 
                   7003:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   7004:     * double **newm;
                   7005:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   7006:     */
1.218     brouard  7007:   
                   7008:    /* int movingaverage(); */
                   7009:    double **dnewm,**doldm;
                   7010:    double **dnewmp,**doldmp;
                   7011:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  7012:    int first=0;
1.218     brouard  7013:    int k;
                   7014:    double *xp;
1.279     brouard  7015:    double **gp, **gm;  /**< for var eij */
                   7016:    double ***gradg, ***trgradg; /**< for var eij */
                   7017:    double **gradgp, **trgradgp; /**< for var p point j */
                   7018:    double *gpp, *gmp; /**< for var p point j */
                   7019:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  7020:    double ***p3mat;
                   7021:    double age,agelim, hf;
                   7022:    /* double ***mobaverage; */
                   7023:    int theta;
                   7024:    char digit[4];
                   7025:    char digitp[25];
                   7026: 
                   7027:    char fileresprobmorprev[FILENAMELENGTH];
                   7028: 
                   7029:    if(popbased==1){
                   7030:      if(mobilav!=0)
                   7031:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7032:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7033:    }
                   7034:    else 
                   7035:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  7036: 
1.218     brouard  7037:    /* if (mobilav!=0) { */
                   7038:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7039:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7040:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7041:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7042:    /*   } */
                   7043:    /* } */
                   7044: 
                   7045:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7046:    sprintf(digit,"%-d",ij);
                   7047:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7048:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7049:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7050:    strcat(fileresprobmorprev,fileresu);
                   7051:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7052:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7053:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7054:    }
                   7055:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7056:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7057:    pstamp(ficresprobmorprev);
                   7058:    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  7059:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7060: 
                   7061:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7062:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7063:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7064:    /* } */
                   7065:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7066:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7067:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7068:    }
1.337     brouard  7069:    /* for(j=1;j<=cptcoveff;j++)  */
                   7070:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7071:    fprintf(ficresprobmorprev,"\n");
                   7072: 
1.218     brouard  7073:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7074:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7075:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7076:      for(i=1; i<=nlstate;i++)
                   7077:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7078:    }  
                   7079:    fprintf(ficresprobmorprev,"\n");
                   7080:   
                   7081:    fprintf(ficgp,"\n# Routine varevsij");
                   7082:    fprintf(ficgp,"\nunset title \n");
                   7083:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7084:    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");
                   7085:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7086: 
1.218     brouard  7087:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7088:    pstamp(ficresvij);
                   7089:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7090:    if(popbased==1)
                   7091:      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);
                   7092:    else
                   7093:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7094:    fprintf(ficresvij,"# Age");
                   7095:    for(i=1; i<=nlstate;i++)
                   7096:      for(j=1; j<=nlstate;j++)
                   7097:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7098:    fprintf(ficresvij,"\n");
                   7099: 
                   7100:    xp=vector(1,npar);
                   7101:    dnewm=matrix(1,nlstate,1,npar);
                   7102:    doldm=matrix(1,nlstate,1,nlstate);
                   7103:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7104:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7105: 
                   7106:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7107:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7108:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7109:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7110:   
1.218     brouard  7111:    if(estepm < stepm){
                   7112:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7113:    }
                   7114:    else  hstepm=estepm;   
                   7115:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7116:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7117:       nhstepm is the number of hstepm from age to agelim 
                   7118:       nstepm is the number of stepm from age to agelim. 
                   7119:       Look at function hpijx to understand why because of memory size limitations, 
                   7120:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7121:       survival function given by stepm (the optimization length). Unfortunately it
                   7122:       means that if the survival funtion is printed every two years of age and if
                   7123:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7124:       results. So we changed our mind and took the option of the best precision.
                   7125:    */
                   7126:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7127:    agelim = AGESUP;
                   7128:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7129:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7130:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7131:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7132:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7133:      gp=matrix(0,nhstepm,1,nlstate);
                   7134:      gm=matrix(0,nhstepm,1,nlstate);
                   7135:                
                   7136:                
                   7137:      for(theta=1; theta <=npar; theta++){
                   7138:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7139:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7140:        }
1.279     brouard  7141:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7142:        * returns into prlim .
1.288     brouard  7143:        */
1.242     brouard  7144:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7145: 
                   7146:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7147:        if (popbased==1) {
                   7148:         if(mobilav ==0){
                   7149:           for(i=1; i<=nlstate;i++)
                   7150:             prlim[i][i]=probs[(int)age][i][ij];
                   7151:         }else{ /* mobilav */ 
                   7152:           for(i=1; i<=nlstate;i++)
                   7153:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7154:         }
                   7155:        }
1.295     brouard  7156:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7157:        */                      
                   7158:        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  7159:        /**< 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  7160:        * at horizon h in state j including mortality.
                   7161:        */
1.218     brouard  7162:        for(j=1; j<= nlstate; j++){
                   7163:         for(h=0; h<=nhstepm; h++){
                   7164:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7165:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7166:         }
                   7167:        }
1.279     brouard  7168:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7169:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7170:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7171:        */
                   7172:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7173:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7174:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7175:        }
                   7176:        
                   7177:        /* Again with minus shift */
1.218     brouard  7178:                        
                   7179:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7180:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7181: 
1.242     brouard  7182:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7183:                        
                   7184:        if (popbased==1) {
                   7185:         if(mobilav ==0){
                   7186:           for(i=1; i<=nlstate;i++)
                   7187:             prlim[i][i]=probs[(int)age][i][ij];
                   7188:         }else{ /* mobilav */ 
                   7189:           for(i=1; i<=nlstate;i++)
                   7190:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7191:         }
                   7192:        }
                   7193:                        
1.235     brouard  7194:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7195:                        
                   7196:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7197:         for(h=0; h<=nhstepm; h++){
                   7198:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7199:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7200:         }
                   7201:        }
                   7202:        /* This for computing probability of death (h=1 means
                   7203:          computed over hstepm matrices product = hstepm*stepm months) 
                   7204:          as a weighted average of prlim.
                   7205:        */
                   7206:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7207:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7208:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7209:        }    
1.279     brouard  7210:        /* end shifting computations */
                   7211: 
                   7212:        /**< Computing gradient matrix at horizon h 
                   7213:        */
1.218     brouard  7214:        for(j=1; j<= nlstate; j++) /* vareij */
                   7215:         for(h=0; h<=nhstepm; h++){
                   7216:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7217:         }
1.279     brouard  7218:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7219:        */
                   7220:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7221:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7222:        }
                   7223:                        
                   7224:      } /* End theta */
1.279     brouard  7225:      
                   7226:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7227:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7228:                
                   7229:      for(h=0; h<=nhstepm; h++) /* veij */
                   7230:        for(j=1; j<=nlstate;j++)
                   7231:         for(theta=1; theta <=npar; theta++)
                   7232:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7233:                
                   7234:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7235:        for(theta=1; theta <=npar; theta++)
                   7236:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7237:      /**< as well as its transposed matrix 
                   7238:       */               
1.218     brouard  7239:                
                   7240:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7241:      for(i=1;i<=nlstate;i++)
                   7242:        for(j=1;j<=nlstate;j++)
                   7243:         vareij[i][j][(int)age] =0.;
1.279     brouard  7244: 
                   7245:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7246:       * and k (nhstepm) formula 15 of article
                   7247:       * Lievre-Brouard-Heathcote
                   7248:       */
                   7249:      
1.218     brouard  7250:      for(h=0;h<=nhstepm;h++){
                   7251:        for(k=0;k<=nhstepm;k++){
                   7252:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7253:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7254:         for(i=1;i<=nlstate;i++)
                   7255:           for(j=1;j<=nlstate;j++)
                   7256:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7257:        }
                   7258:      }
                   7259:                
1.279     brouard  7260:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7261:       * p.j overall mortality formula 49 but computed directly because
                   7262:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7263:       * wix is independent of theta.
                   7264:       */
1.218     brouard  7265:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7266:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7267:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7268:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7269:         varppt[j][i]=doldmp[j][i];
                   7270:      /* end ppptj */
                   7271:      /*  x centered again */
                   7272:                
1.242     brouard  7273:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7274:                
                   7275:      if (popbased==1) {
                   7276:        if(mobilav ==0){
                   7277:         for(i=1; i<=nlstate;i++)
                   7278:           prlim[i][i]=probs[(int)age][i][ij];
                   7279:        }else{ /* mobilav */ 
                   7280:         for(i=1; i<=nlstate;i++)
                   7281:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7282:        }
                   7283:      }
                   7284:                
                   7285:      /* This for computing probability of death (h=1 means
                   7286:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7287:        as a weighted average of prlim.
                   7288:      */
1.235     brouard  7289:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7290:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7291:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7292:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7293:      }    
                   7294:      /* end probability of death */
                   7295:                
                   7296:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7297:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7298:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7299:        for(i=1; i<=nlstate;i++){
                   7300:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7301:        }
                   7302:      } 
                   7303:      fprintf(ficresprobmorprev,"\n");
                   7304:                
                   7305:      fprintf(ficresvij,"%.0f ",age );
                   7306:      for(i=1; i<=nlstate;i++)
                   7307:        for(j=1; j<=nlstate;j++){
                   7308:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7309:        }
                   7310:      fprintf(ficresvij,"\n");
                   7311:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7312:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7313:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7314:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7315:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7316:    } /* End age */
                   7317:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7318:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7319:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7320:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7321:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7322:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7323:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7324:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7325:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7326:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7327:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7328:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7329:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7330:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7331:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7332:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7333:    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);
                   7334:    /*  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  7335:     */
1.218     brouard  7336:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7337:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7338: 
1.218     brouard  7339:    free_vector(xp,1,npar);
                   7340:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7341:    free_matrix(dnewm,1,nlstate,1,npar);
                   7342:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7343:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7344:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7345:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7346:    fclose(ficresprobmorprev);
                   7347:    fflush(ficgp);
                   7348:    fflush(fichtm); 
                   7349:  }  /* end varevsij */
1.126     brouard  7350: 
                   7351: /************ Variance of prevlim ******************/
1.269     brouard  7352:  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  7353: {
1.205     brouard  7354:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7355:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7356: 
1.268     brouard  7357:   double **dnewmpar,**doldm;
1.126     brouard  7358:   int i, j, nhstepm, hstepm;
                   7359:   double *xp;
                   7360:   double *gp, *gm;
                   7361:   double **gradg, **trgradg;
1.208     brouard  7362:   double **mgm, **mgp;
1.126     brouard  7363:   double age,agelim;
                   7364:   int theta;
                   7365:   
                   7366:   pstamp(ficresvpl);
1.288     brouard  7367:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7368:   fprintf(ficresvpl,"# Age ");
                   7369:   if(nresult >=1)
                   7370:     fprintf(ficresvpl," Result# ");
1.126     brouard  7371:   for(i=1; i<=nlstate;i++)
                   7372:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7373:   fprintf(ficresvpl,"\n");
                   7374: 
                   7375:   xp=vector(1,npar);
1.268     brouard  7376:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7377:   doldm=matrix(1,nlstate,1,nlstate);
                   7378:   
                   7379:   hstepm=1*YEARM; /* Every year of age */
                   7380:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7381:   agelim = AGESUP;
                   7382:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7383:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7384:     if (stepm >= YEARM) hstepm=1;
                   7385:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7386:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7387:     mgp=matrix(1,npar,1,nlstate);
                   7388:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7389:     gp=vector(1,nlstate);
                   7390:     gm=vector(1,nlstate);
                   7391: 
                   7392:     for(theta=1; theta <=npar; theta++){
                   7393:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7394:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7395:       }
1.288     brouard  7396:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7397:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7398:       /* else */
                   7399:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7400:       for(i=1;i<=nlstate;i++){
1.126     brouard  7401:        gp[i] = prlim[i][i];
1.208     brouard  7402:        mgp[theta][i] = prlim[i][i];
                   7403:       }
1.126     brouard  7404:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7405:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7406:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7407:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7408:       /* else */
                   7409:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7410:       for(i=1;i<=nlstate;i++){
1.126     brouard  7411:        gm[i] = prlim[i][i];
1.208     brouard  7412:        mgm[theta][i] = prlim[i][i];
                   7413:       }
1.126     brouard  7414:       for(i=1;i<=nlstate;i++)
                   7415:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7416:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7417:     } /* End theta */
                   7418: 
                   7419:     trgradg =matrix(1,nlstate,1,npar);
                   7420: 
                   7421:     for(j=1; j<=nlstate;j++)
                   7422:       for(theta=1; theta <=npar; theta++)
                   7423:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7424:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7425:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7426:     /*   for(j=1; j<=nlstate;j++){ */
                   7427:     /*         printf(" %d ",j); */
                   7428:     /*         for(theta=1; theta <=npar; theta++) */
                   7429:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7430:     /*         printf("\n "); */
                   7431:     /*   } */
                   7432:     /* } */
                   7433:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7434:     /*   printf("\n gradg %d ",(int)age); */
                   7435:     /*   for(j=1; j<=nlstate;j++){ */
                   7436:     /*         printf("%d ",j); */
                   7437:     /*         for(theta=1; theta <=npar; theta++) */
                   7438:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7439:     /*         printf("\n "); */
                   7440:     /*   } */
                   7441:     /* } */
1.126     brouard  7442: 
                   7443:     for(i=1;i<=nlstate;i++)
                   7444:       varpl[i][(int)age] =0.;
1.209     brouard  7445:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7446:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7447:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7448:     }else{
1.268     brouard  7449:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7450:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7451:     }
1.126     brouard  7452:     for(i=1;i<=nlstate;i++)
                   7453:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7454: 
                   7455:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7456:     if(nresult >=1)
                   7457:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7458:     for(i=1; i<=nlstate;i++){
1.126     brouard  7459:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7460:       /* for(j=1;j<=nlstate;j++) */
                   7461:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7462:     }
1.126     brouard  7463:     fprintf(ficresvpl,"\n");
                   7464:     free_vector(gp,1,nlstate);
                   7465:     free_vector(gm,1,nlstate);
1.208     brouard  7466:     free_matrix(mgm,1,npar,1,nlstate);
                   7467:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7468:     free_matrix(gradg,1,npar,1,nlstate);
                   7469:     free_matrix(trgradg,1,nlstate,1,npar);
                   7470:   } /* End age */
                   7471: 
                   7472:   free_vector(xp,1,npar);
                   7473:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7474:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7475: 
                   7476: }
                   7477: 
                   7478: 
                   7479: /************ Variance of backprevalence limit ******************/
1.269     brouard  7480:  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  7481: {
                   7482:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7483:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7484: 
                   7485:   double **dnewmpar,**doldm;
                   7486:   int i, j, nhstepm, hstepm;
                   7487:   double *xp;
                   7488:   double *gp, *gm;
                   7489:   double **gradg, **trgradg;
                   7490:   double **mgm, **mgp;
                   7491:   double age,agelim;
                   7492:   int theta;
                   7493:   
                   7494:   pstamp(ficresvbl);
                   7495:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7496:   fprintf(ficresvbl,"# Age ");
                   7497:   if(nresult >=1)
                   7498:     fprintf(ficresvbl," Result# ");
                   7499:   for(i=1; i<=nlstate;i++)
                   7500:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7501:   fprintf(ficresvbl,"\n");
                   7502: 
                   7503:   xp=vector(1,npar);
                   7504:   dnewmpar=matrix(1,nlstate,1,npar);
                   7505:   doldm=matrix(1,nlstate,1,nlstate);
                   7506:   
                   7507:   hstepm=1*YEARM; /* Every year of age */
                   7508:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7509:   agelim = AGEINF;
                   7510:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7511:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7512:     if (stepm >= YEARM) hstepm=1;
                   7513:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7514:     gradg=matrix(1,npar,1,nlstate);
                   7515:     mgp=matrix(1,npar,1,nlstate);
                   7516:     mgm=matrix(1,npar,1,nlstate);
                   7517:     gp=vector(1,nlstate);
                   7518:     gm=vector(1,nlstate);
                   7519: 
                   7520:     for(theta=1; theta <=npar; theta++){
                   7521:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7522:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7523:       }
                   7524:       if(mobilavproj > 0 )
                   7525:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7526:       else
                   7527:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7528:       for(i=1;i<=nlstate;i++){
                   7529:        gp[i] = bprlim[i][i];
                   7530:        mgp[theta][i] = bprlim[i][i];
                   7531:       }
                   7532:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7533:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7534:        if(mobilavproj > 0 )
                   7535:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7536:        else
                   7537:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7538:       for(i=1;i<=nlstate;i++){
                   7539:        gm[i] = bprlim[i][i];
                   7540:        mgm[theta][i] = bprlim[i][i];
                   7541:       }
                   7542:       for(i=1;i<=nlstate;i++)
                   7543:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7544:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7545:     } /* End theta */
                   7546: 
                   7547:     trgradg =matrix(1,nlstate,1,npar);
                   7548: 
                   7549:     for(j=1; j<=nlstate;j++)
                   7550:       for(theta=1; theta <=npar; theta++)
                   7551:        trgradg[j][theta]=gradg[theta][j];
                   7552:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7553:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7554:     /*   for(j=1; j<=nlstate;j++){ */
                   7555:     /*         printf(" %d ",j); */
                   7556:     /*         for(theta=1; theta <=npar; theta++) */
                   7557:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7558:     /*         printf("\n "); */
                   7559:     /*   } */
                   7560:     /* } */
                   7561:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7562:     /*   printf("\n gradg %d ",(int)age); */
                   7563:     /*   for(j=1; j<=nlstate;j++){ */
                   7564:     /*         printf("%d ",j); */
                   7565:     /*         for(theta=1; theta <=npar; theta++) */
                   7566:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7567:     /*         printf("\n "); */
                   7568:     /*   } */
                   7569:     /* } */
                   7570: 
                   7571:     for(i=1;i<=nlstate;i++)
                   7572:       varbpl[i][(int)age] =0.;
                   7573:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7574:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7575:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7576:     }else{
                   7577:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7578:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7579:     }
                   7580:     for(i=1;i<=nlstate;i++)
                   7581:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7582: 
                   7583:     fprintf(ficresvbl,"%.0f ",age );
                   7584:     if(nresult >=1)
                   7585:       fprintf(ficresvbl,"%d ",nres );
                   7586:     for(i=1; i<=nlstate;i++)
                   7587:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7588:     fprintf(ficresvbl,"\n");
                   7589:     free_vector(gp,1,nlstate);
                   7590:     free_vector(gm,1,nlstate);
                   7591:     free_matrix(mgm,1,npar,1,nlstate);
                   7592:     free_matrix(mgp,1,npar,1,nlstate);
                   7593:     free_matrix(gradg,1,npar,1,nlstate);
                   7594:     free_matrix(trgradg,1,nlstate,1,npar);
                   7595:   } /* End age */
                   7596: 
                   7597:   free_vector(xp,1,npar);
                   7598:   free_matrix(doldm,1,nlstate,1,npar);
                   7599:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7600: 
                   7601: }
                   7602: 
                   7603: /************ Variance of one-step probabilities  ******************/
                   7604: 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  7605:  {
                   7606:    int i, j=0,  k1, l1, tj;
                   7607:    int k2, l2, j1,  z1;
                   7608:    int k=0, l;
                   7609:    int first=1, first1, first2;
1.326     brouard  7610:    int nres=0; /* New */
1.222     brouard  7611:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7612:    double **dnewm,**doldm;
                   7613:    double *xp;
                   7614:    double *gp, *gm;
                   7615:    double **gradg, **trgradg;
                   7616:    double **mu;
                   7617:    double age, cov[NCOVMAX+1];
                   7618:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7619:    int theta;
                   7620:    char fileresprob[FILENAMELENGTH];
                   7621:    char fileresprobcov[FILENAMELENGTH];
                   7622:    char fileresprobcor[FILENAMELENGTH];
                   7623:    double ***varpij;
                   7624: 
                   7625:    strcpy(fileresprob,"PROB_"); 
                   7626:    strcat(fileresprob,fileres);
                   7627:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7628:      printf("Problem with resultfile: %s\n", fileresprob);
                   7629:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7630:    }
                   7631:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7632:    strcat(fileresprobcov,fileresu);
                   7633:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7634:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7635:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7636:    }
                   7637:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7638:    strcat(fileresprobcor,fileresu);
                   7639:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7640:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7641:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7642:    }
                   7643:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7644:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7645:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7646:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7647:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7648:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7649:    pstamp(ficresprob);
                   7650:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7651:    fprintf(ficresprob,"# Age");
                   7652:    pstamp(ficresprobcov);
                   7653:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7654:    fprintf(ficresprobcov,"# Age");
                   7655:    pstamp(ficresprobcor);
                   7656:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7657:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7658: 
                   7659: 
1.222     brouard  7660:    for(i=1; i<=nlstate;i++)
                   7661:      for(j=1; j<=(nlstate+ndeath);j++){
                   7662:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7663:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7664:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7665:      }  
                   7666:    /* fprintf(ficresprob,"\n");
                   7667:       fprintf(ficresprobcov,"\n");
                   7668:       fprintf(ficresprobcor,"\n");
                   7669:    */
                   7670:    xp=vector(1,npar);
                   7671:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7672:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7673:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7674:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7675:    first=1;
                   7676:    fprintf(ficgp,"\n# Routine varprob");
                   7677:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7678:    fprintf(fichtm,"\n");
                   7679: 
1.288     brouard  7680:    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  7681:    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);
                   7682:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7683: and drawn. It helps understanding how is the covariance between two incidences.\
                   7684:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7685:    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  7686: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7687: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7688: standard deviations wide on each axis. <br>\
                   7689:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7690:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7691: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7692: 
1.222     brouard  7693:    cov[1]=1;
                   7694:    /* tj=cptcoveff; */
1.225     brouard  7695:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7696:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7697:    j1=0;
1.332     brouard  7698: 
                   7699:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7700:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7701:      /* 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  7702:      if(tj != 1 && TKresult[nres]!= j1)
                   7703:        continue;
                   7704: 
                   7705:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7706:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7707:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7708:      if  (cptcovn>0) {
1.334     brouard  7709:        fprintf(ficresprob, "\n#********** Variable ");
                   7710:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7711:        fprintf(ficgp, "\n#********** Variable ");
                   7712:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7713:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7714: 
                   7715:        /* Including quantitative variables of the resultline to be done */
                   7716:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7717:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7718:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7719:         /* 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  7720:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7721:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7722:             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  */
                   7723:             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  */
                   7724:             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  */
                   7725:             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  */
                   7726:             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  */
                   7727:             fprintf(ficresprob,"fixed ");
                   7728:             fprintf(ficresprobcov,"fixed ");
                   7729:             fprintf(ficgp,"fixed ");
                   7730:             fprintf(fichtmcov,"fixed ");
                   7731:             fprintf(ficresprobcor,"fixed ");
                   7732:           }else{
                   7733:             fprintf(ficresprob,"varyi ");
                   7734:             fprintf(ficresprobcov,"varyi ");
                   7735:             fprintf(ficgp,"varyi ");
                   7736:             fprintf(fichtmcov,"varyi ");
                   7737:             fprintf(ficresprobcor,"varyi ");
                   7738:           }
                   7739:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7740:           /* For each selected (single) quantitative value */
1.337     brouard  7741:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7742:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7743:             fprintf(ficresprob,"fixed ");
                   7744:             fprintf(ficresprobcov,"fixed ");
                   7745:             fprintf(ficgp,"fixed ");
                   7746:             fprintf(fichtmcov,"fixed ");
                   7747:             fprintf(ficresprobcor,"fixed ");
                   7748:           }else{
                   7749:             fprintf(ficresprob,"varyi ");
                   7750:             fprintf(ficresprobcov,"varyi ");
                   7751:             fprintf(ficgp,"varyi ");
                   7752:             fprintf(fichtmcov,"varyi ");
                   7753:             fprintf(ficresprobcor,"varyi ");
                   7754:           }
                   7755:         }else{
                   7756:           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 */
                   7757:           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 */
                   7758:           exit(1);
                   7759:         }
                   7760:        } /* End loop on variable of this resultline */
                   7761:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7762:        fprintf(ficresprob, "**********\n#\n");
                   7763:        fprintf(ficresprobcov, "**********\n#\n");
                   7764:        fprintf(ficgp, "**********\n#\n");
                   7765:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7766:        fprintf(ficresprobcor, "**********\n#");    
                   7767:        if(invalidvarcomb[j1]){
                   7768:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7769:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7770:         continue;
                   7771:        }
                   7772:      }
                   7773:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7774:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7775:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7776:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7777:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7778:        cov[2]=age;
                   7779:        if(nagesqr==1)
                   7780:         cov[3]= age*age;
1.334     brouard  7781:        /* New code end of combination but for each resultline */
                   7782:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7783:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7784:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7785:         }else{
1.334     brouard  7786:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7787:         }
1.334     brouard  7788:        }/* End of loop on model equation */
                   7789: /* Old code */
                   7790:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7791:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7792:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7793:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7794:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7795:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7796:        /*                                                                  * 1  1 1 1 1 */
                   7797:        /*                                                                  * 2  2 1 1 1 */
                   7798:        /*                                                                  * 3  1 2 1 1 */
                   7799:        /*                                                                  *\/ */
                   7800:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7801:        /* } */
                   7802:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7803:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7804:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7805:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7806:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7807:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7808:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7809:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7810:        /*         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]); */
                   7811:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7812:        /*         /\* exit(1); *\/ */
                   7813:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7814:        /*       } */
                   7815:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7816:        /* } */
                   7817:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7818:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7819:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7820:        /*           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]])]; */
                   7821:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7822:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7823:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7824:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7825:        /*         } */
                   7826:        /*       }else{ */
                   7827:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7828:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7829:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7830:        /*         }else{ */
                   7831:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7832:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7833:        /*         } */
                   7834:        /*       } */
                   7835:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7836:        /* } */                 
1.326     brouard  7837: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7838:        for(theta=1; theta <=npar; theta++){
                   7839:         for(i=1; i<=npar; i++)
                   7840:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7841:                                
1.222     brouard  7842:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7843:                                
1.222     brouard  7844:         k=0;
                   7845:         for(i=1; i<= (nlstate); i++){
                   7846:           for(j=1; j<=(nlstate+ndeath);j++){
                   7847:             k=k+1;
                   7848:             gp[k]=pmmij[i][j];
                   7849:           }
                   7850:         }
1.220     brouard  7851:                                
1.222     brouard  7852:         for(i=1; i<=npar; i++)
                   7853:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7854:                                
1.222     brouard  7855:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7856:         k=0;
                   7857:         for(i=1; i<=(nlstate); i++){
                   7858:           for(j=1; j<=(nlstate+ndeath);j++){
                   7859:             k=k+1;
                   7860:             gm[k]=pmmij[i][j];
                   7861:           }
                   7862:         }
1.220     brouard  7863:                                
1.222     brouard  7864:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7865:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7866:        }
1.126     brouard  7867: 
1.222     brouard  7868:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7869:         for(theta=1; theta <=npar; theta++)
                   7870:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7871:                        
1.222     brouard  7872:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7873:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7874:                        
1.222     brouard  7875:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7876:                        
1.222     brouard  7877:        k=0;
                   7878:        for(i=1; i<=(nlstate); i++){
                   7879:         for(j=1; j<=(nlstate+ndeath);j++){
                   7880:           k=k+1;
                   7881:           mu[k][(int) age]=pmmij[i][j];
                   7882:         }
                   7883:        }
                   7884:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7885:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7886:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7887:                        
1.222     brouard  7888:        /*printf("\n%d ",(int)age);
                   7889:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7890:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7891:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7892:         }*/
1.220     brouard  7893:                        
1.222     brouard  7894:        fprintf(ficresprob,"\n%d ",(int)age);
                   7895:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7896:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7897:                        
1.222     brouard  7898:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7899:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7900:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7901:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7902:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7903:        }
                   7904:        i=0;
                   7905:        for (k=1; k<=(nlstate);k++){
                   7906:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7907:           i++;
                   7908:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7909:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7910:           for (j=1; j<=i;j++){
                   7911:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7912:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7913:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7914:           }
                   7915:         }
                   7916:        }/* end of loop for state */
                   7917:      } /* end of loop for age */
                   7918:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7919:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7920:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7921:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7922:     
                   7923:      /* Confidence intervalle of pij  */
                   7924:      /*
                   7925:        fprintf(ficgp,"\nunset parametric;unset label");
                   7926:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7927:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7928:        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);
                   7929:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7930:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7931:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7932:      */
                   7933:                
                   7934:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7935:      first1=1;first2=2;
                   7936:      for (k2=1; k2<=(nlstate);k2++){
                   7937:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7938:         if(l2==k2) continue;
                   7939:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7940:         for (k1=1; k1<=(nlstate);k1++){
                   7941:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7942:             if(l1==k1) continue;
                   7943:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7944:             if(i<=j) continue;
                   7945:             for (age=bage; age<=fage; age ++){ 
                   7946:               if ((int)age %5==0){
                   7947:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7948:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7949:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7950:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7951:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7952:                 c12=cv12/sqrt(v1*v2);
                   7953:                 /* Computing eigen value of matrix of covariance */
                   7954:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7955:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7956:                 if ((lc2 <0) || (lc1 <0) ){
                   7957:                   if(first2==1){
                   7958:                     first1=0;
                   7959:                     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);
                   7960:                   }
                   7961:                   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);
                   7962:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7963:                   /* lc2=fabs(lc2); */
                   7964:                 }
1.220     brouard  7965:                                                                
1.222     brouard  7966:                 /* Eigen vectors */
1.280     brouard  7967:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7968:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7969:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7970:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7971:                 }else
                   7972:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7973:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7974:                 v21=(lc1-v1)/cv12*v11;
                   7975:                 v12=-v21;
                   7976:                 v22=v11;
                   7977:                 tnalp=v21/v11;
                   7978:                 if(first1==1){
                   7979:                   first1=0;
                   7980:                   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);
                   7981:                 }
                   7982:                 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);
                   7983:                 /*printf(fignu*/
                   7984:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7985:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7986:                 if(first==1){
                   7987:                   first=0;
                   7988:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7989:                   fprintf(ficgp,"\nset parametric;unset label");
                   7990:                   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);
                   7991:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7992:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7993:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7994: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7995:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7996:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7997:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7998:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7999:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8000:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8001:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8002:                   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  8003:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   8004:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  8005:                 }else{
                   8006:                   first=0;
                   8007:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   8008:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8009:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8010:                   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  8011:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   8012:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  8013:                 }/* if first */
                   8014:               } /* age mod 5 */
                   8015:             } /* end loop age */
                   8016:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8017:             first=1;
                   8018:           } /*l12 */
                   8019:         } /* k12 */
                   8020:        } /*l1 */
                   8021:      }/* k1 */
1.332     brouard  8022:    }  /* loop on combination of covariates j1 */
1.326     brouard  8023:    } /* loop on nres */
1.222     brouard  8024:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8025:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8026:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8027:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8028:    free_vector(xp,1,npar);
                   8029:    fclose(ficresprob);
                   8030:    fclose(ficresprobcov);
                   8031:    fclose(ficresprobcor);
                   8032:    fflush(ficgp);
                   8033:    fflush(fichtmcov);
                   8034:  }
1.126     brouard  8035: 
                   8036: 
                   8037: /******************* Printing html file ***********/
1.201     brouard  8038: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8039:                  int lastpass, int stepm, int weightopt, char model[],\
                   8040:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8041:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8042:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8043:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8044:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8045:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8046:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8047:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8048: </ul>");
1.319     brouard  8049: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8050: /* </ul>", model); */
1.214     brouard  8051:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8052:    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",
                   8053:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8054:    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  8055:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8056:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8057:    fprintf(fichtm,"\
                   8058:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8059:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8060:    fprintf(fichtm,"\
1.217     brouard  8061:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8062:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8063:    fprintf(fichtm,"\
1.288     brouard  8064:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8065:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8066:    fprintf(fichtm,"\
1.288     brouard  8067:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8068:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8069:    fprintf(fichtm,"\
1.211     brouard  8070:  - (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  8071:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8072:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8073:    if(prevfcast==1){
                   8074:      fprintf(fichtm,"\
                   8075:  - Prevalence projections by age and states:                           \
1.201     brouard  8076:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8077:    }
1.126     brouard  8078: 
                   8079: 
1.225     brouard  8080:    m=pow(2,cptcoveff);
1.222     brouard  8081:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8082: 
1.317     brouard  8083:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8084: 
                   8085:    jj1=0;
                   8086: 
                   8087:    fprintf(fichtm," \n<ul>");
1.337     brouard  8088:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8089:      /* k1=nres; */
1.338     brouard  8090:      k1=TKresult[nres];
                   8091:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8092:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8093:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8094:    /*     continue; */
1.264     brouard  8095:      jj1++;
                   8096:      if (cptcovn > 0) {
                   8097:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8098:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8099:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8100:        }
1.337     brouard  8101:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8102:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8103:        /* } */
                   8104:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8105:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8106:        /* } */
1.264     brouard  8107:        fprintf(fichtm,"\">");
                   8108:        
                   8109:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8110:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8111:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8112:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8113:        }
1.337     brouard  8114:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8115:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8116:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8117:        /* } */
                   8118:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8119:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8120:        /* } */
1.264     brouard  8121:        if(invalidvarcomb[k1]){
                   8122:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8123:         continue;
                   8124:        }
                   8125:        fprintf(fichtm,"</a></li>");
                   8126:      } /* cptcovn >0 */
                   8127:    }
1.317     brouard  8128:    fprintf(fichtm," \n</ul>");
1.264     brouard  8129: 
1.222     brouard  8130:    jj1=0;
1.237     brouard  8131: 
1.337     brouard  8132:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8133:      /* k1=nres; */
1.338     brouard  8134:      k1=TKresult[nres];
                   8135:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8136:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8137:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8138:    /*     continue; */
1.220     brouard  8139: 
1.222     brouard  8140:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8141:      jj1++;
                   8142:      if (cptcovn > 0) {
1.264     brouard  8143:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8144:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8145:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8146:        }
1.337     brouard  8147:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8148:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8149:        /* } */
1.264     brouard  8150:        fprintf(fichtm,"\"</a>");
                   8151:  
1.222     brouard  8152:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8153:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8154:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8155:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8156:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8157:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8158:        }
1.230     brouard  8159:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8160:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8161:        if(invalidvarcomb[k1]){
                   8162:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8163:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8164:         continue;
                   8165:        }
                   8166:      }
                   8167:      /* aij, bij */
1.259     brouard  8168:      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  8169: <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  8170:      /* Pij */
1.241     brouard  8171:      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> \
                   8172: <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  8173:      /* Quasi-incidences */
                   8174:      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  8175:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8176:  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  8177: 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> \
                   8178: <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  8179:      /* Survival functions (period) in state j */
                   8180:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8181:        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);
                   8182:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8183:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8184:      }
                   8185:      /* State specific survival functions (period) */
                   8186:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8187:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8188:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8189:  <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);
                   8190:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8191:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8192:      }
1.288     brouard  8193:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8194:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8195:        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  8196:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8197:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8198:      }
1.296     brouard  8199:      if(prevbcast==1){
1.288     brouard  8200:        /* Backward prevalence in each health state */
1.222     brouard  8201:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8202:         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);
                   8203:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8204:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8205:        }
1.217     brouard  8206:      }
1.222     brouard  8207:      if(prevfcast==1){
1.288     brouard  8208:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8209:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8210:         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);
                   8211:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8212:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8213:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8214:        }
                   8215:      }
1.296     brouard  8216:      if(prevbcast==1){
1.268     brouard  8217:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8218:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8219:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8220:  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 \
                   8221:  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  8222: 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);
                   8223:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8224:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8225:        }
                   8226:      }
1.220     brouard  8227:         
1.222     brouard  8228:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8229:        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);
                   8230:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8231:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8232:      }
                   8233:      /* } /\* end i1 *\/ */
1.337     brouard  8234:    }/* End k1=nres */
1.222     brouard  8235:    fprintf(fichtm,"</ul>");
1.126     brouard  8236: 
1.222     brouard  8237:    fprintf(fichtm,"\
1.126     brouard  8238: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8239:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8240:  - 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  8241: But because parameters are usually highly correlated (a higher incidence of disability \
                   8242: and a higher incidence of recovery can give very close observed transition) it might \
                   8243: be very useful to look not only at linear confidence intervals estimated from the \
                   8244: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8245: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8246: covariance matrix of the one-step probabilities. \
                   8247: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8248: 
1.222     brouard  8249:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8250:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8251:    fprintf(fichtm,"\
1.126     brouard  8252:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8253:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8254: 
1.222     brouard  8255:    fprintf(fichtm,"\
1.126     brouard  8256:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8257:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8258:    fprintf(fichtm,"\
1.126     brouard  8259:  - 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): \
                   8260:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8261:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8262:    fprintf(fichtm,"\
1.126     brouard  8263:  - (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): \
                   8264:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8265:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8266:    fprintf(fichtm,"\
1.288     brouard  8267:  - 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  8268:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8269:    fprintf(fichtm,"\
1.128     brouard  8270:  - 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  8271:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8272:    fprintf(fichtm,"\
1.288     brouard  8273:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8274:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8275: 
                   8276: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8277: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8278: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8279: /*     <br>",fileres,fileres,fileres,fileres); */
                   8280: /*  else  */
1.338     brouard  8281: /*    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  8282:    fflush(fichtm);
1.126     brouard  8283: 
1.225     brouard  8284:    m=pow(2,cptcoveff);
1.222     brouard  8285:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8286: 
1.317     brouard  8287:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8288: 
                   8289:   jj1=0;
                   8290: 
                   8291:    fprintf(fichtm," \n<ul>");
1.337     brouard  8292:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8293:      /* k1=nres; */
1.338     brouard  8294:      k1=TKresult[nres];
1.337     brouard  8295:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8296:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8297:      /*   continue; */
1.317     brouard  8298:      jj1++;
                   8299:      if (cptcovn > 0) {
                   8300:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8301:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8302:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8303:        }
                   8304:        fprintf(fichtm,"\">");
                   8305:        
                   8306:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8307:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8308:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8309:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8310:        }
                   8311:        if(invalidvarcomb[k1]){
                   8312:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8313:         continue;
                   8314:        }
                   8315:        fprintf(fichtm,"</a></li>");
                   8316:      } /* cptcovn >0 */
1.337     brouard  8317:    } /* End nres */
1.317     brouard  8318:    fprintf(fichtm," \n</ul>");
                   8319: 
1.222     brouard  8320:    jj1=0;
1.237     brouard  8321: 
1.241     brouard  8322:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8323:      /* k1=nres; */
1.338     brouard  8324:      k1=TKresult[nres];
                   8325:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8326:      /* for(k1=1; k1<=m;k1++){ */
                   8327:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8328:      /*   continue; */
1.222     brouard  8329:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8330:      jj1++;
1.126     brouard  8331:      if (cptcovn > 0) {
1.317     brouard  8332:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8333:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8334:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8335:        }
                   8336:        fprintf(fichtm,"\"</a>");
                   8337:        
1.126     brouard  8338:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8339:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8340:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8341:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8342:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8343:        }
1.237     brouard  8344: 
1.338     brouard  8345:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8346: 
1.222     brouard  8347:        if(invalidvarcomb[k1]){
                   8348:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8349:         continue;
                   8350:        }
1.337     brouard  8351:      } /* If cptcovn >0 */
1.126     brouard  8352:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8353:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8354: 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);
                   8355:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8356:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8357:      }
                   8358:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8359: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8360: true period expectancies (those weighted with period prevalences are also\
                   8361:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8362:  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);
                   8363:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8364:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8365:      /* } /\* end i1 *\/ */
1.241     brouard  8366:   }/* End nres */
1.222     brouard  8367:    fprintf(fichtm,"</ul>");
                   8368:    fflush(fichtm);
1.126     brouard  8369: }
                   8370: 
                   8371: /******************* Gnuplot file **************/
1.296     brouard  8372: 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  8373: 
1.354     brouard  8374:   char dirfileres[256],optfileres[256];
                   8375:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  8376:   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  8377:   int lv=0, vlv=0, kl=0;
1.130     brouard  8378:   int ng=0;
1.201     brouard  8379:   int vpopbased;
1.223     brouard  8380:   int ioffset; /* variable offset for columns */
1.270     brouard  8381:   int iyearc=1; /* variable column for year of projection  */
                   8382:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8383:   int nres=0; /* Index of resultline */
1.266     brouard  8384:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8385: 
1.126     brouard  8386: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8387: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8388: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8389: /*   } */
                   8390: 
                   8391:   /*#ifdef windows */
                   8392:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8393:   /*#endif */
1.225     brouard  8394:   m=pow(2,cptcoveff);
1.126     brouard  8395: 
1.274     brouard  8396:   /* diagram of the model */
                   8397:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8398:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8399:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8400:   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);
                   8401: 
1.343     brouard  8402:   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  8403:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8404:   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);
                   8405:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8406:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8407:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8408:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8409: 
1.202     brouard  8410:   /* Contribution to likelihood */
                   8411:   /* Plot the probability implied in the likelihood */
1.223     brouard  8412:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8413:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8414:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8415:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8416: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8417:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8418: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8419:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8420:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8421:   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));
                   8422:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8423:   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));
                   8424:   for (i=1; i<= nlstate ; i ++) {
                   8425:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8426:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8427:     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);
                   8428:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8429:       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);
                   8430:     }
                   8431:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8432:   }
                   8433:   /* 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 */               
                   8434:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8435:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8436:   fprintf(ficgp,"\nset out;unset log\n");
                   8437:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8438: 
1.343     brouard  8439:   /* Plot the probability implied in the likelihood by covariate value */
                   8440:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8441:   /* if(debugILK==1){ */
                   8442:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8443:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8444:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  8445:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.355   ! brouard  8446:     /* k=19+nlstate+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
        !          8447:     k=16+nlstate+kf;/*offset because there are 19 columns in the ILK_ file, first cov Vn on col 21 with 4 living states */
1.343     brouard  8448:     for (i=1; i<= nlstate ; i ++) {
                   8449:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8450:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8451:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8452:        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);
                   8453:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8454:          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);
                   8455:        }
                   8456:       }else{
                   8457:        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);
                   8458:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8459:          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);
                   8460:        }
1.343     brouard  8461:       }
                   8462:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8463:     }
                   8464:   } /* End of each covariate dummy */
                   8465:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8466:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8467:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8468:      *  varying                   1     2                                 3       4        5
                   8469:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8470:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8471:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8472:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8473:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8474:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8475:      */
                   8476:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8477:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8478:     /* 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]); */
                   8479:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8480:       /* printf(" %d",ipos); */
                   8481:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8482:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8483:       kk++; /* Position of the ncovv column in ILK_ */
                   8484:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8485:       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)  */
                   8486:        for (i=1; i<= nlstate ; i ++) {
                   8487:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8488:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8489: 
1.348     brouard  8490:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8491:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8492:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8493:            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);
                   8494:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8495:              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);
                   8496:            }
                   8497:          }else{
                   8498:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8499:            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);
                   8500:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8501:              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);
                   8502:            }
                   8503:          }
                   8504:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8505:        }
                   8506:       }/* End if dummy varying */
                   8507:     }else{ /*Product */
                   8508:       /* printf("*"); */
                   8509:       /* fprintf(ficresilk,"*"); */
                   8510:     }
                   8511:     iposold=ipos;
                   8512:   } /* For each time varying covariate */
                   8513:   /* } /\* debugILK==1 *\/ */
                   8514:   /* 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 */               
                   8515:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8516:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8517:   fprintf(ficgp,"\nset out;unset log\n");
                   8518:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8519: 
                   8520: 
                   8521:   
1.126     brouard  8522:   strcpy(dirfileres,optionfilefiname);
                   8523:   strcpy(optfileres,"vpl");
1.223     brouard  8524:   /* 1eme*/
1.238     brouard  8525:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8526:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8527:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8528:        k1=TKresult[nres];
1.338     brouard  8529:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8530:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8531:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8532:        /*   continue; */
1.238     brouard  8533:        /* We are interested in selected combination by the resultline */
1.246     brouard  8534:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8535:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8536:        strcpy(gplotlabel,"(");
1.337     brouard  8537:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8538:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8539:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8540: 
                   8541:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8542:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8543:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8544:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8545:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8546:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8547:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8548:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8549:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8550:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8551:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8552:        /* } */
                   8553:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8554:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8555:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8556:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8557:        }
                   8558:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8559:        /* printf("\n#\n"); */
1.238     brouard  8560:        fprintf(ficgp,"\n#\n");
                   8561:        if(invalidvarcomb[k1]){
1.260     brouard  8562:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8563:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8564:          continue;
                   8565:        }
1.235     brouard  8566:       
1.241     brouard  8567:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8568:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8569:        /* 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  8570:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8571:        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);
                   8572:        /* 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); */
                   8573:       /* k1-1 error should be nres-1*/
1.238     brouard  8574:        for (i=1; i<= nlstate ; i ++) {
                   8575:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8576:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8577:        }
1.288     brouard  8578:        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  8579:        for (i=1; i<= nlstate ; i ++) {
                   8580:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8581:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8582:        } 
1.260     brouard  8583:        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  8584:        for (i=1; i<= nlstate ; i ++) {
                   8585:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8586:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8587:        }  
1.265     brouard  8588:        /* 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)); */
                   8589:        
                   8590:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8591:         if(cptcoveff ==0){
1.271     brouard  8592:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8593:        }else{
                   8594:          kl=0;
                   8595:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8596:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8597:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8598:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8599:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8600:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8601:            vlv= nbcode[Tvaraff[k]][lv];
                   8602:            kl++;
                   8603:            /* 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 *\/ */
                   8604:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8605:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8606:            /* ''  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*/
                   8607:            if(k==cptcoveff){
                   8608:              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], \
                   8609:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8610:            }else{
                   8611:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8612:              kl++;
                   8613:            }
                   8614:          } /* end covariate */
                   8615:        } /* end if no covariate */
                   8616: 
1.296     brouard  8617:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8618:          /* 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  8619:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8620:          if(cptcoveff ==0){
1.245     brouard  8621:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8622:          }else{
                   8623:            kl=0;
                   8624:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8625:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8626:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8627:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8628:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8629:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8630:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8631:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8632:              kl++;
1.238     brouard  8633:              /* 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 *\/ */
                   8634:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8635:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8636:              /* ''  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*/
                   8637:              if(k==cptcoveff){
1.245     brouard  8638:                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  8639:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8640:              }else{
1.332     brouard  8641:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8642:                kl++;
                   8643:              }
                   8644:            } /* end covariate */
                   8645:          } /* end if no covariate */
1.296     brouard  8646:          if(prevbcast == 1){
1.268     brouard  8647:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8648:            /* k1-1 error should be nres-1*/
                   8649:            for (i=1; i<= nlstate ; i ++) {
                   8650:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8651:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8652:            }
1.271     brouard  8653:            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  8654:            for (i=1; i<= nlstate ; i ++) {
                   8655:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8656:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8657:            } 
1.276     brouard  8658:            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  8659:            for (i=1; i<= nlstate ; i ++) {
                   8660:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8661:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8662:            } 
1.274     brouard  8663:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8664:          } /* end if backprojcast */
1.296     brouard  8665:        } /* end if prevbcast */
1.276     brouard  8666:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8667:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8668:       } /* nres */
1.337     brouard  8669:     /* } /\* k1 *\/ */
1.201     brouard  8670:   } /* cpt */
1.235     brouard  8671: 
                   8672:   
1.126     brouard  8673:   /*2 eme*/
1.337     brouard  8674:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8675:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8676:       k1=TKresult[nres];
1.338     brouard  8677:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8678:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8679:       /*       continue; */
1.238     brouard  8680:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8681:       strcpy(gplotlabel,"(");
1.337     brouard  8682:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8683:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8684:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8685:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8686:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8687:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8688:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8689:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8690:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8691:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8692:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8693:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8694:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8695:       /* } */
                   8696:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8697:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8698:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8699:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8700:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8701:       }
1.264     brouard  8702:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8703:       fprintf(ficgp,"\n#\n");
1.223     brouard  8704:       if(invalidvarcomb[k1]){
                   8705:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8706:        continue;
                   8707:       }
1.219     brouard  8708:                        
1.241     brouard  8709:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8710:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8711:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8712:        if(vpopbased==0){
1.238     brouard  8713:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8714:        }else
1.238     brouard  8715:          fprintf(ficgp,"\nreplot ");
                   8716:        for (i=1; i<= nlstate+1 ; i ++) {
                   8717:          k=2*i;
1.261     brouard  8718:          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  8719:          for (j=1; j<= nlstate+1 ; j ++) {
                   8720:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8721:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8722:          }   
                   8723:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8724:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8725:          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  8726:          for (j=1; j<= nlstate+1 ; j ++) {
                   8727:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8728:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8729:          }   
                   8730:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8731:          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  8732:          for (j=1; j<= nlstate+1 ; j ++) {
                   8733:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8734:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8735:          }   
                   8736:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8737:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8738:        } /* state */
                   8739:       } /* vpopbased */
1.264     brouard  8740:       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  8741:     } /* end nres */
1.337     brouard  8742:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8743:        
                   8744:        
                   8745:   /*3eme*/
1.337     brouard  8746:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8747:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8748:       k1=TKresult[nres];
1.338     brouard  8749:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8750:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8751:       /*       continue; */
1.238     brouard  8752: 
1.332     brouard  8753:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8754:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8755:        strcpy(gplotlabel,"(");
1.337     brouard  8756:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8757:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8758:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8759:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8760:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8761:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8762:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8763:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8764:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8765:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8766:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8767:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8768:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8769:        /* } */
                   8770:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8771:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8772:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8773:        }
1.264     brouard  8774:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8775:        fprintf(ficgp,"\n#\n");
                   8776:        if(invalidvarcomb[k1]){
                   8777:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8778:          continue;
                   8779:        }
                   8780:                        
                   8781:        /*       k=2+nlstate*(2*cpt-2); */
                   8782:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8783:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8784:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8785:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8786: 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  8787:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8788:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8789:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8790:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8791:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8792:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8793:                                
1.238     brouard  8794:        */
                   8795:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8796:          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  8797:          /*    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  8798:                                
1.238     brouard  8799:        } 
1.261     brouard  8800:        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  8801:       }
1.264     brouard  8802:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8803:     } /* end nres */
1.337     brouard  8804:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8805:   
1.223     brouard  8806:   /* 4eme */
1.201     brouard  8807:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8808:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8809:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8810:       k1=TKresult[nres];
1.338     brouard  8811:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8812:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8813:       /*       continue; */
1.238     brouard  8814:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8815:        strcpy(gplotlabel,"(");
1.337     brouard  8816:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8817:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8818:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8819:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8820:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8821:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8822:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8823:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8824:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8825:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8826:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8827:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8828:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8829:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8830:        /* } */
                   8831:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8832:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8833:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8834:        }       
1.264     brouard  8835:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8836:        fprintf(ficgp,"\n#\n");
                   8837:        if(invalidvarcomb[k1]){
                   8838:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8839:          continue;
1.223     brouard  8840:        }
1.238     brouard  8841:       
1.241     brouard  8842:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8843:        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  8844:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8845: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8846:        k=3;
                   8847:        for (i=1; i<= nlstate ; i ++){
                   8848:          if(i==1){
                   8849:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8850:          }else{
                   8851:            fprintf(ficgp,", '' ");
                   8852:          }
                   8853:          l=(nlstate+ndeath)*(i-1)+1;
                   8854:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8855:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8856:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8857:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8858:        } /* nlstate */
1.264     brouard  8859:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8860:       } /* end cpt state*/ 
                   8861:     } /* end nres */
1.337     brouard  8862:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8863: 
1.220     brouard  8864: /* 5eme */
1.201     brouard  8865:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8866:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8867:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8868:       k1=TKresult[nres];
1.338     brouard  8869:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8870:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8871:       /*       continue; */
1.238     brouard  8872:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8873:        strcpy(gplotlabel,"(");
1.238     brouard  8874:        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  8875:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8876:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8877:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8878:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8879:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8880:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8881:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8882:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8883:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8884:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8885:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8886:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8887:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8888:        /* } */
                   8889:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8890:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8891:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8892:        }       
1.264     brouard  8893:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8894:        fprintf(ficgp,"\n#\n");
                   8895:        if(invalidvarcomb[k1]){
                   8896:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8897:          continue;
                   8898:        }
1.227     brouard  8899:       
1.241     brouard  8900:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8901:        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  8902:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8903: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8904:        k=3;
                   8905:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8906:          if(j==1)
                   8907:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8908:          else
                   8909:            fprintf(ficgp,", '' ");
                   8910:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8911:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8912:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8913:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8914:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8915:        } /* nlstate */
                   8916:        fprintf(ficgp,", '' ");
                   8917:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8918:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8919:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8920:          if(j < nlstate)
                   8921:            fprintf(ficgp,"$%d +",k+l);
                   8922:          else
                   8923:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8924:        }
1.264     brouard  8925:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8926:       } /* end cpt state*/ 
1.337     brouard  8927:     /* } /\* end covariate *\/   */
1.238     brouard  8928:   } /* end nres */
1.227     brouard  8929:   
1.220     brouard  8930: /* 6eme */
1.202     brouard  8931:   /* CV preval stable (period) for each covariate */
1.337     brouard  8932:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8933:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8934:      k1=TKresult[nres];
1.338     brouard  8935:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8936:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8937:      /*  continue; */
1.255     brouard  8938:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8939:       strcpy(gplotlabel,"(");      
1.288     brouard  8940:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8941:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8942:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8943:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8944:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8945:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8946:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8947:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8948:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8949:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8950:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8951:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8952:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8953:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8954:       /* } */
                   8955:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8956:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8957:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8958:       }        
1.264     brouard  8959:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8960:       fprintf(ficgp,"\n#\n");
1.223     brouard  8961:       if(invalidvarcomb[k1]){
1.227     brouard  8962:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8963:        continue;
1.223     brouard  8964:       }
1.227     brouard  8965:       
1.241     brouard  8966:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8967:       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  8968:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8969: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8970:       k=3; /* Offset */
1.255     brouard  8971:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8972:        if(i==1)
                   8973:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8974:        else
                   8975:          fprintf(ficgp,", '' ");
1.255     brouard  8976:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8977:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8978:        for (j=2; j<= nlstate ; j ++)
                   8979:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8980:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8981:       } /* nlstate */
1.264     brouard  8982:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8983:     } /* end cpt state*/ 
                   8984:   } /* end covariate */  
1.227     brouard  8985:   
                   8986:   
1.220     brouard  8987: /* 7eme */
1.296     brouard  8988:   if(prevbcast == 1){
1.288     brouard  8989:     /* CV backward prevalence  for each covariate */
1.337     brouard  8990:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8991:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8992:       k1=TKresult[nres];
1.338     brouard  8993:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8994:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8995:       /*       continue; */
1.268     brouard  8996:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8997:        strcpy(gplotlabel,"(");      
1.288     brouard  8998:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8999:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9000:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9001:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9002:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9003:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9004:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9005:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9006:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9007:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9008:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9009:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9010:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9011:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9012:        /* } */
                   9013:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9014:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9015:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9016:        }       
1.264     brouard  9017:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9018:        fprintf(ficgp,"\n#\n");
                   9019:        if(invalidvarcomb[k1]){
                   9020:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9021:          continue;
                   9022:        }
                   9023:        
1.241     brouard  9024:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  9025:        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  9026:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9027: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  9028:        k=3; /* Offset */
1.268     brouard  9029:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  9030:          if(i==1)
                   9031:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9032:          else
                   9033:            fprintf(ficgp,", '' ");
                   9034:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  9035:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  9036:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9037:          /* 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  9038:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9039:          /* for (j=2; j<= nlstate ; j ++) */
                   9040:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9041:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9042:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9043:        } /* nlstate */
1.264     brouard  9044:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9045:       } /* end cpt state*/ 
                   9046:     } /* end covariate */  
1.296     brouard  9047:   } /* End if prevbcast */
1.218     brouard  9048:   
1.223     brouard  9049:   /* 8eme */
1.218     brouard  9050:   if(prevfcast==1){
1.288     brouard  9051:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9052:     
1.337     brouard  9053:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9054:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9055:       k1=TKresult[nres];
1.338     brouard  9056:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9057:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9058:       /*       continue; */
1.211     brouard  9059:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9060:        strcpy(gplotlabel,"(");      
1.288     brouard  9061:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9062:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9063:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9064:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9065:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9066:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9067:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9068:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9069:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9070:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9071:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9072:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9073:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9074:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9075:        /* } */
                   9076:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9077:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9078:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9079:        }       
1.264     brouard  9080:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9081:        fprintf(ficgp,"\n#\n");
                   9082:        if(invalidvarcomb[k1]){
                   9083:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9084:          continue;
                   9085:        }
                   9086:        
                   9087:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9088:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9089:        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  9090:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9091: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9092: 
                   9093:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9094:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9095:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9096:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9097:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9098:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9099:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9100:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9101:          if(i==istart){
1.227     brouard  9102:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9103:          }else{
                   9104:            fprintf(ficgp,",\\\n '' ");
                   9105:          }
                   9106:          if(cptcoveff ==0){ /* No covariate */
                   9107:            ioffset=2; /* Age is in 2 */
                   9108:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9109:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9110:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9111:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9112:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9113:            if(i==nlstate+1){
1.270     brouard  9114:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9115:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9116:              fprintf(ficgp,",\\\n '' ");
                   9117:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9118:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9119:                     offyear,                           \
1.268     brouard  9120:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9121:            }else
1.227     brouard  9122:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9123:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9124:          }else{ /* more than 2 covariates */
1.270     brouard  9125:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9126:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9127:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9128:            iyearc=ioffset-1;
                   9129:            iagec=ioffset;
1.227     brouard  9130:            fprintf(ficgp," u %d:(",ioffset); 
                   9131:            kl=0;
                   9132:            strcpy(gplotcondition,"(");
1.351     brouard  9133:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  9134:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  9135:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9136:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9137:              lv=Tvresult[nres][k];
                   9138:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  9139:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9140:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9141:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9142:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  9143:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  9144:              kl++;
1.351     brouard  9145:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9146:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  9147:              kl++;
1.351     brouard  9148:              if(k <cptcovs && cptcovs>1)
1.227     brouard  9149:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9150:            }
                   9151:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9152:            /* 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 *\/ */
                   9153:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9154:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9155:            /* ''  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*/
                   9156:            if(i==nlstate+1){
1.270     brouard  9157:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9158:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9159:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9160:              fprintf(ficgp," u %d:(",iagec); 
                   9161:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9162:                      iyearc, iagec, offyear,                           \
                   9163:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9164: /*  '' 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  9165:            }else{
                   9166:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9167:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9168:            }
                   9169:          } /* end if covariate */
                   9170:        } /* nlstate */
1.264     brouard  9171:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9172:       } /* end cpt state*/
                   9173:     } /* end covariate */
                   9174:   } /* End if prevfcast */
1.227     brouard  9175:   
1.296     brouard  9176:   if(prevbcast==1){
1.268     brouard  9177:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9178:     
1.337     brouard  9179:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9180:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9181:      k1=TKresult[nres];
1.338     brouard  9182:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9183:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9184:        /*      continue; */
1.268     brouard  9185:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9186:        strcpy(gplotlabel,"(");      
                   9187:        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  9188:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9189:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9190:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9191:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9192:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9193:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9194:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9195:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9196:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9197:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9198:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9199:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9200:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9201:        /* } */
                   9202:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9203:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9204:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9205:        }       
                   9206:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9207:        fprintf(ficgp,"\n#\n");
                   9208:        if(invalidvarcomb[k1]){
                   9209:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9210:          continue;
                   9211:        }
                   9212:        
                   9213:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9214:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9215:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9216:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9217: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9218: 
                   9219:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9220:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9221:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9222:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9223:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9224:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9225:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9226:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9227:          if(i==istart){
                   9228:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9229:          }else{
                   9230:            fprintf(ficgp,",\\\n '' ");
                   9231:          }
1.351     brouard  9232:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   9233:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  9234:            ioffset=2; /* Age is in 2 */
                   9235:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9236:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9237:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9238:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9239:            fprintf(ficgp," u %d:(", ioffset); 
                   9240:            if(i==nlstate+1){
1.270     brouard  9241:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9242:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9243:              fprintf(ficgp,",\\\n '' ");
                   9244:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9245:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9246:                     offbyear,                          \
                   9247:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9248:            }else
                   9249:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9250:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9251:          }else{ /* more than 2 covariates */
1.270     brouard  9252:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9253:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9254:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9255:            iyearc=ioffset-1;
                   9256:            iagec=ioffset;
1.268     brouard  9257:            fprintf(ficgp," u %d:(",ioffset); 
                   9258:            kl=0;
                   9259:            strcpy(gplotcondition,"(");
1.337     brouard  9260:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9261:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9262:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9263:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9264:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9265:                lv=Tvresult[nres][k];
                   9266:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9267:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9268:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9269:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9270:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9271:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9272:                kl++;
                   9273:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9274:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9275:                kl++;
1.338     brouard  9276:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9277:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9278:              }
1.268     brouard  9279:            }
                   9280:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9281:            /* 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 *\/ */
                   9282:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9283:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9284:            /* ''  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*/
                   9285:            if(i==nlstate+1){
1.270     brouard  9286:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9287:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9288:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9289:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9290:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9291:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9292:                      iyearc,iagec,offbyear,                            \
                   9293:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9294: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9295:            }else{
                   9296:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9297:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9298:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9299:            }
                   9300:          } /* end if covariate */
                   9301:        } /* nlstate */
                   9302:        fprintf(ficgp,"\nset out; unset label;\n");
                   9303:       } /* end cpt state*/
                   9304:     } /* end covariate */
1.296     brouard  9305:   } /* End if prevbcast */
1.268     brouard  9306:   
1.227     brouard  9307:   
1.238     brouard  9308:   /* 9eme writing MLE parameters */
                   9309:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9310:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9311:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9312:     for(k=1; k <=(nlstate+ndeath); k++){
                   9313:       if (k != i) {
1.227     brouard  9314:        fprintf(ficgp,"#   current state %d\n",k);
                   9315:        for(j=1; j <=ncovmodel; j++){
                   9316:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9317:          jk++; 
                   9318:        }
                   9319:        fprintf(ficgp,"\n");
1.126     brouard  9320:       }
                   9321:     }
1.223     brouard  9322:   }
1.187     brouard  9323:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9324:   
1.145     brouard  9325:   /*goto avoid;*/
1.238     brouard  9326:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9327:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9328:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9329:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9330:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9331:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9332:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9333:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9334:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9335:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9336:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9337:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9338:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9339:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9340:   fprintf(ficgp,"#\n");
1.223     brouard  9341:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9342:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9343:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9344:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  9345:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   9346:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  9347:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9348:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9349:      /* k1=nres; */
1.338     brouard  9350:       k1=TKresult[nres];
                   9351:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9352:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9353:       strcpy(gplotlabel,"(");
1.276     brouard  9354:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9355:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9356:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9357:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9358:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9359:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9360:       }
                   9361:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9362:       /*       continue; */
                   9363:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9364:       /* strcpy(gplotlabel,"("); */
                   9365:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9366:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9367:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9368:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9369:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9370:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9371:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9372:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9373:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9374:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9375:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9376:       /* } */
                   9377:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9378:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9379:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9380:       /* }      */
1.264     brouard  9381:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9382:       fprintf(ficgp,"\n#\n");
1.264     brouard  9383:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9384:       fprintf(ficgp,"\nset key outside ");
                   9385:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9386:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9387:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9388:       if (ng==1){
                   9389:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9390:        fprintf(ficgp,"\nunset log y");
                   9391:       }else if (ng==2){
                   9392:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9393:        fprintf(ficgp,"\nset log y");
                   9394:       }else if (ng==3){
                   9395:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9396:        fprintf(ficgp,"\nset log y");
                   9397:       }else
                   9398:        fprintf(ficgp,"\nunset title ");
                   9399:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9400:       i=1;
                   9401:       for(k2=1; k2<=nlstate; k2++) {
                   9402:        k3=i;
                   9403:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9404:          if (k != k2){
                   9405:            switch( ng) {
                   9406:            case 1:
                   9407:              if(nagesqr==0)
                   9408:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9409:              else /* nagesqr =1 */
                   9410:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9411:              break;
                   9412:            case 2: /* ng=2 */
                   9413:              if(nagesqr==0)
                   9414:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9415:              else /* nagesqr =1 */
                   9416:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9417:              break;
                   9418:            case 3:
                   9419:              if(nagesqr==0)
                   9420:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9421:              else /* nagesqr =1 */
                   9422:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9423:              break;
                   9424:            }
                   9425:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9426:            ijp=1; /* product no age */
                   9427:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9428:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9429:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9430:              switch(Typevar[j]){
                   9431:              case 1:
                   9432:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9433:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9434:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9435:                      if(DummyV[j]==0){/* Bug valgrind */
                   9436:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9437:                      }else{ /* quantitative */
                   9438:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9439:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9440:                      }
                   9441:                      ij++;
1.268     brouard  9442:                    }
1.237     brouard  9443:                  }
1.329     brouard  9444:                }
                   9445:                break;
                   9446:              case 2:
                   9447:                if(cptcovprod >0){
                   9448:                  if(j==Tprod[ijp]) { /* */ 
                   9449:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9450:                    if(ijp <=cptcovprod) { /* Product */
                   9451:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9452:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9453:                          /* 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)]); */
                   9454:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9455:                        }else{ /* Vn is dummy and Vm is quanti */
                   9456:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9457:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9458:                        }
                   9459:                      }else{ /* Vn*Vm Vn is quanti */
                   9460:                        if(DummyV[Tvard[ijp][2]]==0){
                   9461:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9462:                        }else{ /* Both quanti */
                   9463:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9464:                        }
1.268     brouard  9465:                      }
1.329     brouard  9466:                      ijp++;
1.237     brouard  9467:                    }
1.329     brouard  9468:                  } /* end Tprod */
                   9469:                }
                   9470:                break;
1.349     brouard  9471:              case 3:
                   9472:                if(cptcovdageprod >0){
                   9473:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9474:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  9475:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9476:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9477:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9478:                          /* 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)]); */
                   9479:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9480:                        }else{ /* Vn is dummy and Vm is quanti */
                   9481:                          /* 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  9482:                          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  9483:                        }
1.350     brouard  9484:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9485:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  9486:                          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  9487:                        }else{ /* Both quanti */
1.350     brouard  9488:                          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  9489:                        }
                   9490:                      }
                   9491:                      ijp++;
                   9492:                    }
                   9493:                    /* } */ /* end Tprod */
                   9494:                }
                   9495:                break;
1.329     brouard  9496:              case 0:
                   9497:                /* simple covariate */
1.264     brouard  9498:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9499:                if(Dummy[j]==0){
                   9500:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9501:                }else{ /* quantitative */
                   9502:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9503:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9504:                }
1.329     brouard  9505:               /* end simple */
                   9506:                break;
                   9507:              default:
                   9508:                break;
                   9509:              } /* end switch */
1.237     brouard  9510:            } /* end j */
1.329     brouard  9511:          }else{ /* k=k2 */
                   9512:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9513:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9514:            }else
                   9515:              i=i-ncovmodel;
1.223     brouard  9516:          }
1.227     brouard  9517:          
1.223     brouard  9518:          if(ng != 1){
                   9519:            fprintf(ficgp,")/(1");
1.227     brouard  9520:            
1.264     brouard  9521:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9522:              if(nagesqr==0)
1.264     brouard  9523:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9524:              else /* nagesqr =1 */
1.264     brouard  9525:                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  9526:               
1.223     brouard  9527:              ij=1;
1.329     brouard  9528:              ijp=1;
                   9529:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9530:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9531:                switch(Typevar[j]){
                   9532:                case 1:
                   9533:                  if(cptcovage >0){ 
                   9534:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9535:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9536:                        if(DummyV[j]==0){/* Bug valgrind */
                   9537:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9538:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9539:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9540:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9541:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9542:                        }else{ /* quantitative */
                   9543:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9544:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9545:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9546:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9547:                        }
                   9548:                        ij++;
                   9549:                      }
                   9550:                    }
                   9551:                  }
                   9552:                  break;
                   9553:                case 2:
                   9554:                  if(cptcovprod >0){
                   9555:                    if(j==Tprod[ijp]) { /* */ 
                   9556:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9557:                      if(ijp <=cptcovprod) { /* Product */
                   9558:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9559:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9560:                            /* 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)]); */
                   9561:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9562:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9563:                          }else{ /* Vn is dummy and Vm is quanti */
                   9564:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9565:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9566:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9567:                          }
                   9568:                        }else{ /* Vn*Vm Vn is quanti */
                   9569:                          if(DummyV[Tvard[ijp][2]]==0){
                   9570:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9571:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9572:                          }else{ /* Both quanti */
                   9573:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9574:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9575:                          } 
                   9576:                        }
                   9577:                        ijp++;
                   9578:                      }
                   9579:                    } /* end Tprod */
                   9580:                  } /* end if */
                   9581:                  break;
1.349     brouard  9582:                case 3:
                   9583:                  if(cptcovdageprod >0){
                   9584:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9585:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9586:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  9587:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9588:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9589:                            /* 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  9590:                            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  9591:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9592:                          }else{ /* Vn is dummy and Vm is quanti */
                   9593:                            /* 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  9594:                            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  9595:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9596:                          }
                   9597:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  9598:                          if(DummyV[Tvardk[ijp][2]]==0){
                   9599:                            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  9600:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9601:                          }else{ /* Both quanti */
1.350     brouard  9602:                            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  9603:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9604:                          } 
                   9605:                        }
                   9606:                        ijp++;
                   9607:                      }
                   9608:                    /* } /\* end Tprod *\/ */
                   9609:                  } /* end if */
                   9610:                  break;
1.329     brouard  9611:                case 0: 
                   9612:                  /* simple covariate */
                   9613:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9614:                  if(Dummy[j]==0){
                   9615:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9616:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9617:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9618:                  }else{ /* quantitative */
                   9619:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9620:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9621:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9622:                  }
                   9623:                  /* end simple */
                   9624:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9625:                  break;
                   9626:                default:
                   9627:                  break;
                   9628:                } /* end switch */
1.223     brouard  9629:              }
                   9630:              fprintf(ficgp,")");
                   9631:            }
                   9632:            fprintf(ficgp,")");
                   9633:            if(ng ==2)
1.276     brouard  9634:              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  9635:            else /* ng= 3 */
1.276     brouard  9636:              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  9637:           }else{ /* end ng <> 1 */
1.223     brouard  9638:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9639:              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  9640:          }
                   9641:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9642:            fprintf(ficgp,",");
                   9643:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9644:            fprintf(ficgp,",");
                   9645:          i=i+ncovmodel;
                   9646:        } /* end k */
                   9647:       } /* end k2 */
1.276     brouard  9648:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9649:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9650:     } /* end resultline */
1.223     brouard  9651:   } /* end ng */
                   9652:   /* avoid: */
                   9653:   fflush(ficgp); 
1.126     brouard  9654: }  /* end gnuplot */
                   9655: 
                   9656: 
                   9657: /*************** Moving average **************/
1.219     brouard  9658: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9659:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9660:    
1.222     brouard  9661:    int i, cpt, cptcod;
                   9662:    int modcovmax =1;
                   9663:    int mobilavrange, mob;
                   9664:    int iage=0;
1.288     brouard  9665:    int firstA1=0, firstA2=0;
1.222     brouard  9666: 
1.266     brouard  9667:    double sum=0., sumr=0.;
1.222     brouard  9668:    double age;
1.266     brouard  9669:    double *sumnewp, *sumnewm, *sumnewmr;
                   9670:    double *agemingood, *agemaxgood; 
                   9671:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9672:   
                   9673:   
1.278     brouard  9674:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9675:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9676: 
                   9677:    sumnewp = vector(1,ncovcombmax);
                   9678:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9679:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9680:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9681:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9682:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9683:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9684: 
                   9685:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9686:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9687:      sumnewp[cptcod]=0.;
1.266     brouard  9688:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9689:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9690:    }
                   9691:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9692:   
1.266     brouard  9693:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9694:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9695:      else mobilavrange=mobilav;
                   9696:      for (age=bage; age<=fage; age++)
                   9697:        for (i=1; i<=nlstate;i++)
                   9698:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9699:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9700:      /* We keep the original values on the extreme ages bage, fage and for 
                   9701:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9702:        we use a 5 terms etc. until the borders are no more concerned. 
                   9703:      */ 
                   9704:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9705:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9706:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9707:           sumnewm[cptcod]=0.;
                   9708:           for (i=1; i<=nlstate;i++){
1.222     brouard  9709:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9710:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9711:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9712:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9713:             }
                   9714:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9715:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9716:           } /* end i */
                   9717:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9718:         } /* end cptcod */
1.222     brouard  9719:        }/* end age */
                   9720:      }/* end mob */
1.266     brouard  9721:    }else{
                   9722:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9723:      return -1;
1.266     brouard  9724:    }
                   9725: 
                   9726:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9727:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9728:      if(invalidvarcomb[cptcod]){
                   9729:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9730:        continue;
                   9731:      }
1.219     brouard  9732: 
1.266     brouard  9733:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9734:        sumnewm[cptcod]=0.;
                   9735:        sumnewmr[cptcod]=0.;
                   9736:        for (i=1; i<=nlstate;i++){
                   9737:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9738:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9739:        }
                   9740:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9741:         agemingoodr[cptcod]=age;
                   9742:        }
                   9743:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9744:           agemingood[cptcod]=age;
                   9745:        }
                   9746:      } /* age */
                   9747:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9748:        sumnewm[cptcod]=0.;
1.266     brouard  9749:        sumnewmr[cptcod]=0.;
1.222     brouard  9750:        for (i=1; i<=nlstate;i++){
                   9751:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9752:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9753:        }
                   9754:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9755:         agemaxgoodr[cptcod]=age;
1.222     brouard  9756:        }
                   9757:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9758:         agemaxgood[cptcod]=age;
                   9759:        }
                   9760:      } /* age */
                   9761:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9762:      /* but they will change */
1.288     brouard  9763:      firstA1=0;firstA2=0;
1.266     brouard  9764:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9765:        sumnewm[cptcod]=0.;
                   9766:        sumnewmr[cptcod]=0.;
                   9767:        for (i=1; i<=nlstate;i++){
                   9768:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9769:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9770:        }
                   9771:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9772:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9773:           agemaxgoodr[cptcod]=age;  /* age min */
                   9774:           for (i=1; i<=nlstate;i++)
                   9775:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9776:         }else{ /* bad we change the value with the values of good ages */
                   9777:           for (i=1; i<=nlstate;i++){
                   9778:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9779:           } /* i */
                   9780:         } /* end bad */
                   9781:        }else{
                   9782:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9783:           agemaxgood[cptcod]=age;
                   9784:         }else{ /* bad we change the value with the values of good ages */
                   9785:           for (i=1; i<=nlstate;i++){
                   9786:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9787:           } /* i */
                   9788:         } /* end bad */
                   9789:        }/* end else */
                   9790:        sum=0.;sumr=0.;
                   9791:        for (i=1; i<=nlstate;i++){
                   9792:         sum+=mobaverage[(int)age][i][cptcod];
                   9793:         sumr+=probs[(int)age][i][cptcod];
                   9794:        }
                   9795:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9796:         if(!firstA1){
                   9797:           firstA1=1;
                   9798:           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);
                   9799:         }
                   9800:         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  9801:        } /* end bad */
                   9802:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9803:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9804:         if(!firstA2){
                   9805:           firstA2=1;
                   9806:           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);
                   9807:         }
                   9808:         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  9809:        } /* end bad */
                   9810:      }/* age */
1.266     brouard  9811: 
                   9812:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9813:        sumnewm[cptcod]=0.;
1.266     brouard  9814:        sumnewmr[cptcod]=0.;
1.222     brouard  9815:        for (i=1; i<=nlstate;i++){
                   9816:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9817:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9818:        } 
                   9819:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9820:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9821:           agemingoodr[cptcod]=age;
                   9822:           for (i=1; i<=nlstate;i++)
                   9823:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9824:         }else{ /* bad we change the value with the values of good ages */
                   9825:           for (i=1; i<=nlstate;i++){
                   9826:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9827:           } /* i */
                   9828:         } /* end bad */
                   9829:        }else{
                   9830:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9831:           agemingood[cptcod]=age;
                   9832:         }else{ /* bad */
                   9833:           for (i=1; i<=nlstate;i++){
                   9834:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9835:           } /* i */
                   9836:         } /* end bad */
                   9837:        }/* end else */
                   9838:        sum=0.;sumr=0.;
                   9839:        for (i=1; i<=nlstate;i++){
                   9840:         sum+=mobaverage[(int)age][i][cptcod];
                   9841:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9842:        }
1.266     brouard  9843:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9844:         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  9845:        } /* end bad */
                   9846:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9847:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9848:         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  9849:        } /* end bad */
                   9850:      }/* age */
1.266     brouard  9851: 
1.222     brouard  9852:                
                   9853:      for (age=bage; age<=fage; age++){
1.235     brouard  9854:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9855:        sumnewp[cptcod]=0.;
                   9856:        sumnewm[cptcod]=0.;
                   9857:        for (i=1; i<=nlstate;i++){
                   9858:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9859:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9860:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9861:        }
                   9862:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9863:      }
                   9864:      /* printf("\n"); */
                   9865:      /* } */
1.266     brouard  9866: 
1.222     brouard  9867:      /* brutal averaging */
1.266     brouard  9868:      /* for (i=1; i<=nlstate;i++){ */
                   9869:      /*   for (age=1; age<=bage; age++){ */
                   9870:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9871:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9872:      /*   }     */
                   9873:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9874:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9875:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9876:      /*   } */
                   9877:      /* } /\* end i status *\/ */
                   9878:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9879:      /*   for (age=1; age<=AGESUP; age++){ */
                   9880:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9881:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9882:      /*   } */
                   9883:      /* } */
1.222     brouard  9884:    }/* end cptcod */
1.266     brouard  9885:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9886:    free_vector(agemaxgood,1, ncovcombmax);
                   9887:    free_vector(agemingood,1, ncovcombmax);
                   9888:    free_vector(agemingoodr,1, ncovcombmax);
                   9889:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9890:    free_vector(sumnewm,1, ncovcombmax);
                   9891:    free_vector(sumnewp,1, ncovcombmax);
                   9892:    return 0;
                   9893:  }/* End movingaverage */
1.218     brouard  9894:  
1.126     brouard  9895: 
1.296     brouard  9896:  
1.126     brouard  9897: /************** Forecasting ******************/
1.296     brouard  9898: /* 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)*/
                   9899: 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){
                   9900:   /* dateintemean, mean date of interviews
                   9901:      dateprojd, year, month, day of starting projection 
                   9902:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9903:      agemin, agemax range of age
                   9904:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9905:   */
1.296     brouard  9906:   /* double anprojd, mprojd, jprojd; */
                   9907:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9908:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9909:   double agec; /* generic age */
1.296     brouard  9910:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9911:   double *popeffectif,*popcount;
                   9912:   double ***p3mat;
1.218     brouard  9913:   /* double ***mobaverage; */
1.126     brouard  9914:   char fileresf[FILENAMELENGTH];
                   9915: 
                   9916:   agelim=AGESUP;
1.211     brouard  9917:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9918:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9919:      We still use firstpass and lastpass as another selection.
                   9920:   */
1.214     brouard  9921:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9922:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9923:  
1.201     brouard  9924:   strcpy(fileresf,"F_"); 
                   9925:   strcat(fileresf,fileresu);
1.126     brouard  9926:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9927:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9928:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9929:   }
1.235     brouard  9930:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9931:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9932: 
1.225     brouard  9933:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9934: 
                   9935: 
                   9936:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9937:   if (stepm<=12) stepsize=1;
                   9938:   if(estepm < stepm){
                   9939:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9940:   }
1.270     brouard  9941:   else{
                   9942:     hstepm=estepm;   
                   9943:   }
                   9944:   if(estepm > stepm){ /* Yes every two year */
                   9945:     stepsize=2;
                   9946:   }
1.296     brouard  9947:   hstepm=hstepm/stepm;
1.126     brouard  9948: 
1.296     brouard  9949:   
                   9950:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9951:   /*                              fractional in yp1 *\/ */
                   9952:   /* aintmean=yp; */
                   9953:   /* yp2=modf((yp1*12),&yp); */
                   9954:   /* mintmean=yp; */
                   9955:   /* yp1=modf((yp2*30.5),&yp); */
                   9956:   /* jintmean=yp; */
                   9957:   /* if(jintmean==0) jintmean=1; */
                   9958:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9959: 
1.296     brouard  9960: 
                   9961:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9962:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9963:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  9964:   /* i1=pow(2,cptcoveff); */
                   9965:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  9966:   
1.296     brouard  9967:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9968:   
                   9969:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9970:   
1.126     brouard  9971: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  9972:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9973:     k=TKresult[nres];
                   9974:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   9975:     /*  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) *\/ */
                   9976:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   9977:     /*   continue; */
                   9978:     /* if(invalidvarcomb[k]){ */
                   9979:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   9980:     /*   continue; */
                   9981:     /* } */
1.227     brouard  9982:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  9983:     for(j=1;j<=cptcovs;j++){
                   9984:       /* for(j=1;j<=cptcoveff;j++) { */
                   9985:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   9986:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9987:     /* } */
                   9988:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9989:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9990:     /* } */
                   9991:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  9992:     }
1.351     brouard  9993:  
1.227     brouard  9994:     fprintf(ficresf," yearproj age");
                   9995:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9996:       for(i=1; i<=nlstate;i++)               
                   9997:        fprintf(ficresf," p%d%d",i,j);
                   9998:       fprintf(ficresf," wp.%d",j);
                   9999:     }
1.296     brouard  10000:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  10001:       fprintf(ficresf,"\n");
1.296     brouard  10002:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  10003:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   10004:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  10005:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   10006:        nhstepm = nhstepm/hstepm; 
                   10007:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10008:        oldm=oldms;savm=savms;
1.268     brouard  10009:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  10010:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  10011:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  10012:        for (h=0; h<=nhstepm; h++){
                   10013:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  10014:            break;
                   10015:          }
                   10016:        }
                   10017:        fprintf(ficresf,"\n");
1.351     brouard  10018:        /* for(j=1;j<=cptcoveff;j++)  */
                   10019:        for(j=1;j<=cptcovs;j++) 
                   10020:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  10021:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  10022:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  10023:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  10024:        
                   10025:        for(j=1; j<=nlstate+ndeath;j++) {
                   10026:          ppij=0.;
                   10027:          for(i=1; i<=nlstate;i++) {
1.278     brouard  10028:            if (mobilav>=1)
                   10029:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10030:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10031:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10032:            }
1.268     brouard  10033:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10034:          } /* end i */
                   10035:          fprintf(ficresf," %.3f", ppij);
                   10036:        }/* end j */
1.227     brouard  10037:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10038:       } /* end agec */
1.266     brouard  10039:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10040:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  10041:     } /* end yearp */
                   10042:   } /* end  k */
1.219     brouard  10043:        
1.126     brouard  10044:   fclose(ficresf);
1.215     brouard  10045:   printf("End of Computing forecasting \n");
                   10046:   fprintf(ficlog,"End of Computing forecasting\n");
                   10047: 
1.126     brouard  10048: }
                   10049: 
1.269     brouard  10050: /************** Back Forecasting ******************/
1.296     brouard  10051:  /* 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){ */
                   10052:  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){
                   10053:   /* back1, year, month, day of starting backprojection
1.267     brouard  10054:      agemin, agemax range of age
                   10055:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10056:      anback2 year of end of backprojection (same day and month as back1).
                   10057:      prevacurrent and prev are prevalences.
1.267     brouard  10058:   */
                   10059:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10060:   double agec; /* generic age */
1.302     brouard  10061:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10062:   double *popeffectif,*popcount;
                   10063:   double ***p3mat;
                   10064:   /* double ***mobaverage; */
                   10065:   char fileresfb[FILENAMELENGTH];
                   10066:  
1.268     brouard  10067:   agelim=AGEINF;
1.267     brouard  10068:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10069:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10070:      We still use firstpass and lastpass as another selection.
                   10071:   */
                   10072:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10073:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10074: 
                   10075:   /*Do we need to compute prevalence again?*/
                   10076: 
                   10077:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10078:   
                   10079:   strcpy(fileresfb,"FB_");
                   10080:   strcat(fileresfb,fileresu);
                   10081:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10082:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10083:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10084:   }
                   10085:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10086:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10087:   
                   10088:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10089:   
                   10090:    
                   10091:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10092:   if (stepm<=12) stepsize=1;
                   10093:   if(estepm < stepm){
                   10094:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10095:   }
1.270     brouard  10096:   else{
                   10097:     hstepm=estepm;   
                   10098:   }
                   10099:   if(estepm >= stepm){ /* Yes every two year */
                   10100:     stepsize=2;
                   10101:   }
1.267     brouard  10102:   
                   10103:   hstepm=hstepm/stepm;
1.296     brouard  10104:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10105:   /*                              fractional in yp1 *\/ */
                   10106:   /* aintmean=yp; */
                   10107:   /* yp2=modf((yp1*12),&yp); */
                   10108:   /* mintmean=yp; */
                   10109:   /* yp1=modf((yp2*30.5),&yp); */
                   10110:   /* jintmean=yp; */
                   10111:   /* if(jintmean==0) jintmean=1; */
                   10112:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10113:   
1.351     brouard  10114:   /* i1=pow(2,cptcoveff); */
                   10115:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  10116:   
1.296     brouard  10117:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10118:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10119:   
                   10120:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10121:   
1.351     brouard  10122:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10123:     k=TKresult[nres];
                   10124:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10125:   /* for(k=1; k<=i1;k++){ */
                   10126:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   10127:   /*     continue; */
                   10128:   /*   if(invalidvarcomb[k]){ */
                   10129:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10130:   /*     continue; */
                   10131:   /*   } */
1.268     brouard  10132:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  10133:     for(j=1;j<=cptcovs;j++){
                   10134:     /* for(j=1;j<=cptcoveff;j++) { */
                   10135:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10136:     /* } */
                   10137:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  10138:     }
1.351     brouard  10139:    /*  fprintf(ficrespij,"******\n"); */
                   10140:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10141:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10142:    /*  } */
1.267     brouard  10143:     fprintf(ficresfb," yearbproj age");
                   10144:     for(j=1; j<=nlstate+ndeath;j++){
                   10145:       for(i=1; i<=nlstate;i++)
1.268     brouard  10146:        fprintf(ficresfb," b%d%d",i,j);
                   10147:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10148:     }
1.296     brouard  10149:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10150:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10151:       fprintf(ficresfb,"\n");
1.296     brouard  10152:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10153:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10154:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10155:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10156:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10157:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10158:        nhstepm = nhstepm/hstepm;
                   10159:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10160:        oldm=oldms;savm=savms;
1.268     brouard  10161:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10162:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10163:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10164:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10165:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10166:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10167:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10168:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10169:            break;
                   10170:          }
                   10171:        }
                   10172:        fprintf(ficresfb,"\n");
1.351     brouard  10173:        /* for(j=1;j<=cptcoveff;j++) */
                   10174:        for(j=1;j<=cptcovs;j++)
                   10175:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10176:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  10177:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10178:        for(i=1; i<=nlstate+ndeath;i++) {
                   10179:          ppij=0.;ppi=0.;
                   10180:          for(j=1; j<=nlstate;j++) {
                   10181:            /* if (mobilav==1) */
1.269     brouard  10182:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10183:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10184:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10185:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10186:              /* else { */
                   10187:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10188:              /* } */
1.268     brouard  10189:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10190:          } /* end j */
                   10191:          if(ppi <0.99){
                   10192:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10193:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10194:          }
                   10195:          fprintf(ficresfb," %.3f", ppij);
                   10196:        }/* end j */
1.267     brouard  10197:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10198:       } /* end agec */
                   10199:     } /* end yearp */
                   10200:   } /* end k */
1.217     brouard  10201:   
1.267     brouard  10202:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10203:   
1.267     brouard  10204:   fclose(ficresfb);
                   10205:   printf("End of Computing Back forecasting \n");
                   10206:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10207:        
1.267     brouard  10208: }
1.217     brouard  10209: 
1.269     brouard  10210: /* Variance of prevalence limit: varprlim */
                   10211:  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  10212:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10213:  
                   10214:    char fileresvpl[FILENAMELENGTH];  
                   10215:    FILE *ficresvpl;
                   10216:    double **oldm, **savm;
                   10217:    double **varpl; /* Variances of prevalence limits by age */   
                   10218:    int i1, k, nres, j ;
                   10219:    
                   10220:     strcpy(fileresvpl,"VPL_");
                   10221:     strcat(fileresvpl,fileresu);
                   10222:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10223:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10224:       exit(0);
                   10225:     }
1.288     brouard  10226:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10227:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10228:     
                   10229:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10230:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10231:     
                   10232:     i1=pow(2,cptcoveff);
                   10233:     if (cptcovn < 1){i1=1;}
                   10234: 
1.337     brouard  10235:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10236:        k=TKresult[nres];
1.338     brouard  10237:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10238:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10239:       if(i1 != 1 && TKresult[nres]!= k)
                   10240:        continue;
                   10241:       fprintf(ficresvpl,"\n#****** ");
                   10242:       printf("\n#****** ");
                   10243:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10244:       for(j=1;j<=cptcovs;j++) {
                   10245:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10246:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10247:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10248:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10249:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10250:       }
1.337     brouard  10251:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10252:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10253:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10254:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10255:       /* }      */
1.269     brouard  10256:       fprintf(ficresvpl,"******\n");
                   10257:       printf("******\n");
                   10258:       fprintf(ficlog,"******\n");
                   10259:       
                   10260:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10261:       oldm=oldms;savm=savms;
                   10262:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10263:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10264:       /*}*/
                   10265:     }
                   10266:     
                   10267:     fclose(ficresvpl);
1.288     brouard  10268:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10269:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10270: 
                   10271:  }
                   10272: /* Variance of back prevalence: varbprlim */
                   10273:  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){
                   10274:       /*------- Variance of back (stable) prevalence------*/
                   10275: 
                   10276:    char fileresvbl[FILENAMELENGTH];  
                   10277:    FILE  *ficresvbl;
                   10278: 
                   10279:    double **oldm, **savm;
                   10280:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10281:    int i1, k, nres, j ;
                   10282: 
                   10283:    strcpy(fileresvbl,"VBL_");
                   10284:    strcat(fileresvbl,fileresu);
                   10285:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10286:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10287:      exit(0);
                   10288:    }
                   10289:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10290:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10291:    
                   10292:    
                   10293:    i1=pow(2,cptcoveff);
                   10294:    if (cptcovn < 1){i1=1;}
                   10295:    
1.337     brouard  10296:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10297:      k=TKresult[nres];
1.338     brouard  10298:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10299:     /* for(k=1; k<=i1;k++){ */
                   10300:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10301:     /*          continue; */
1.269     brouard  10302:        fprintf(ficresvbl,"\n#****** ");
                   10303:        printf("\n#****** ");
                   10304:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10305:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10306:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10307:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10308:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10309:        /* for(j=1;j<=cptcoveff;j++) { */
                   10310:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10311:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10312:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10313:        /* } */
                   10314:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10315:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10316:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10317:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10318:        }
                   10319:        fprintf(ficresvbl,"******\n");
                   10320:        printf("******\n");
                   10321:        fprintf(ficlog,"******\n");
                   10322:        
                   10323:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10324:        oldm=oldms;savm=savms;
                   10325:        
                   10326:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10327:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10328:        /*}*/
                   10329:      }
                   10330:    
                   10331:    fclose(ficresvbl);
                   10332:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10333:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10334: 
                   10335:  } /* End of varbprlim */
                   10336: 
1.126     brouard  10337: /************** Forecasting *****not tested NB*************/
1.227     brouard  10338: /* 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  10339:   
1.227     brouard  10340: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10341: /*   int *popage; */
                   10342: /*   double calagedatem, agelim, kk1, kk2; */
                   10343: /*   double *popeffectif,*popcount; */
                   10344: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10345: /*   /\* double ***mobaverage; *\/ */
                   10346: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10347: 
1.227     brouard  10348: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10349: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10350: /*   agelim=AGESUP; */
                   10351: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10352:   
1.227     brouard  10353: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10354:   
                   10355:   
1.227     brouard  10356: /*   strcpy(filerespop,"POP_");  */
                   10357: /*   strcat(filerespop,fileresu); */
                   10358: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10359: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10360: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10361: /*   } */
                   10362: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10363: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10364: 
1.227     brouard  10365: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10366: 
1.227     brouard  10367: /*   /\* if (mobilav!=0) { *\/ */
                   10368: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10369: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10370: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10371: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10372: /*   /\*   } *\/ */
                   10373: /*   /\* } *\/ */
1.126     brouard  10374: 
1.227     brouard  10375: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10376: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10377:   
1.227     brouard  10378: /*   agelim=AGESUP; */
1.126     brouard  10379:   
1.227     brouard  10380: /*   hstepm=1; */
                   10381: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10382:        
1.227     brouard  10383: /*   if (popforecast==1) { */
                   10384: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10385: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10386: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10387: /*     }  */
                   10388: /*     popage=ivector(0,AGESUP); */
                   10389: /*     popeffectif=vector(0,AGESUP); */
                   10390: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10391:     
1.227     brouard  10392: /*     i=1;    */
                   10393: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10394:     
1.227     brouard  10395: /*     imx=i; */
                   10396: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10397: /*   } */
1.218     brouard  10398:   
1.227     brouard  10399: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10400: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10401: /*       k=k+1; */
                   10402: /*       fprintf(ficrespop,"\n#******"); */
                   10403: /*       for(j=1;j<=cptcoveff;j++) { */
                   10404: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10405: /*       } */
                   10406: /*       fprintf(ficrespop,"******\n"); */
                   10407: /*       fprintf(ficrespop,"# Age"); */
                   10408: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10409: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10410:       
1.227     brouard  10411: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10412: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10413:        
1.227     brouard  10414: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10415: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10416: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10417:          
1.227     brouard  10418: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10419: /*       oldm=oldms;savm=savms; */
                   10420: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10421:          
1.227     brouard  10422: /*       for (h=0; h<=nhstepm; h++){ */
                   10423: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10424: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10425: /*         }  */
                   10426: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10427: /*           kk1=0.;kk2=0; */
                   10428: /*           for(i=1; i<=nlstate;i++) {               */
                   10429: /*             if (mobilav==1)  */
                   10430: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10431: /*             else { */
                   10432: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10433: /*             } */
                   10434: /*           } */
                   10435: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10436: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10437: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10438: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10439: /*           } */
                   10440: /*         } */
                   10441: /*         for(i=1; i<=nlstate;i++){ */
                   10442: /*           kk1=0.; */
                   10443: /*           for(j=1; j<=nlstate;j++){ */
                   10444: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10445: /*           } */
                   10446: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10447: /*         } */
1.218     brouard  10448:            
1.227     brouard  10449: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10450: /*           for(j=1; j<=nlstate;j++)  */
                   10451: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10452: /*       } */
                   10453: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10454: /*     } */
                   10455: /*       } */
1.218     brouard  10456:       
1.227     brouard  10457: /*       /\******\/ */
1.218     brouard  10458:       
1.227     brouard  10459: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10460: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10461: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10462: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10463: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10464:          
1.227     brouard  10465: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10466: /*       oldm=oldms;savm=savms; */
                   10467: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10468: /*       for (h=0; h<=nhstepm; h++){ */
                   10469: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10470: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10471: /*         }  */
                   10472: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10473: /*           kk1=0.;kk2=0; */
                   10474: /*           for(i=1; i<=nlstate;i++) {               */
                   10475: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10476: /*           } */
                   10477: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10478: /*         } */
                   10479: /*       } */
                   10480: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10481: /*     } */
                   10482: /*       } */
                   10483: /*     }  */
                   10484: /*   } */
1.218     brouard  10485:   
1.227     brouard  10486: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10487:   
1.227     brouard  10488: /*   if (popforecast==1) { */
                   10489: /*     free_ivector(popage,0,AGESUP); */
                   10490: /*     free_vector(popeffectif,0,AGESUP); */
                   10491: /*     free_vector(popcount,0,AGESUP); */
                   10492: /*   } */
                   10493: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10494: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10495: /*   fclose(ficrespop); */
                   10496: /* } /\* End of popforecast *\/ */
1.218     brouard  10497:  
1.126     brouard  10498: int fileappend(FILE *fichier, char *optionfich)
                   10499: {
                   10500:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10501:     printf("Problem with file: %s\n", optionfich);
                   10502:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10503:     return (0);
                   10504:   }
                   10505:   fflush(fichier);
                   10506:   return (1);
                   10507: }
                   10508: 
                   10509: 
                   10510: /**************** function prwizard **********************/
                   10511: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10512: {
                   10513: 
                   10514:   /* Wizard to print covariance matrix template */
                   10515: 
1.164     brouard  10516:   char ca[32], cb[32];
                   10517:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10518:   int numlinepar;
                   10519: 
                   10520:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10521:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10522:   for(i=1; i <=nlstate; i++){
                   10523:     jj=0;
                   10524:     for(j=1; j <=nlstate+ndeath; j++){
                   10525:       if(j==i) continue;
                   10526:       jj++;
                   10527:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10528:       printf("%1d%1d",i,j);
                   10529:       fprintf(ficparo,"%1d%1d",i,j);
                   10530:       for(k=1; k<=ncovmodel;k++){
                   10531:        /*        printf(" %lf",param[i][j][k]); */
                   10532:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10533:        printf(" 0.");
                   10534:        fprintf(ficparo," 0.");
                   10535:       }
                   10536:       printf("\n");
                   10537:       fprintf(ficparo,"\n");
                   10538:     }
                   10539:   }
                   10540:   printf("# Scales (for hessian or gradient estimation)\n");
                   10541:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10542:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10543:   for(i=1; i <=nlstate; i++){
                   10544:     jj=0;
                   10545:     for(j=1; j <=nlstate+ndeath; j++){
                   10546:       if(j==i) continue;
                   10547:       jj++;
                   10548:       fprintf(ficparo,"%1d%1d",i,j);
                   10549:       printf("%1d%1d",i,j);
                   10550:       fflush(stdout);
                   10551:       for(k=1; k<=ncovmodel;k++){
                   10552:        /*      printf(" %le",delti3[i][j][k]); */
                   10553:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10554:        printf(" 0.");
                   10555:        fprintf(ficparo," 0.");
                   10556:       }
                   10557:       numlinepar++;
                   10558:       printf("\n");
                   10559:       fprintf(ficparo,"\n");
                   10560:     }
                   10561:   }
                   10562:   printf("# Covariance matrix\n");
                   10563: /* # 121 Var(a12)\n\ */
                   10564: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10565: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10566: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10567: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10568: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10569: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10570: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10571:   fflush(stdout);
                   10572:   fprintf(ficparo,"# Covariance matrix\n");
                   10573:   /* # 121 Var(a12)\n\ */
                   10574:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10575:   /* #   ...\n\ */
                   10576:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10577:   
                   10578:   for(itimes=1;itimes<=2;itimes++){
                   10579:     jj=0;
                   10580:     for(i=1; i <=nlstate; i++){
                   10581:       for(j=1; j <=nlstate+ndeath; j++){
                   10582:        if(j==i) continue;
                   10583:        for(k=1; k<=ncovmodel;k++){
                   10584:          jj++;
                   10585:          ca[0]= k+'a'-1;ca[1]='\0';
                   10586:          if(itimes==1){
                   10587:            printf("#%1d%1d%d",i,j,k);
                   10588:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10589:          }else{
                   10590:            printf("%1d%1d%d",i,j,k);
                   10591:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10592:            /*  printf(" %.5le",matcov[i][j]); */
                   10593:          }
                   10594:          ll=0;
                   10595:          for(li=1;li <=nlstate; li++){
                   10596:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10597:              if(lj==li) continue;
                   10598:              for(lk=1;lk<=ncovmodel;lk++){
                   10599:                ll++;
                   10600:                if(ll<=jj){
                   10601:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10602:                  if(ll<jj){
                   10603:                    if(itimes==1){
                   10604:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10605:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10606:                    }else{
                   10607:                      printf(" 0.");
                   10608:                      fprintf(ficparo," 0.");
                   10609:                    }
                   10610:                  }else{
                   10611:                    if(itimes==1){
                   10612:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10613:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10614:                    }else{
                   10615:                      printf(" 0.");
                   10616:                      fprintf(ficparo," 0.");
                   10617:                    }
                   10618:                  }
                   10619:                }
                   10620:              } /* end lk */
                   10621:            } /* end lj */
                   10622:          } /* end li */
                   10623:          printf("\n");
                   10624:          fprintf(ficparo,"\n");
                   10625:          numlinepar++;
                   10626:        } /* end k*/
                   10627:       } /*end j */
                   10628:     } /* end i */
                   10629:   } /* end itimes */
                   10630: 
                   10631: } /* end of prwizard */
                   10632: /******************* Gompertz Likelihood ******************************/
                   10633: double gompertz(double x[])
                   10634: { 
1.302     brouard  10635:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10636:   int i,n=0; /* n is the size of the sample */
                   10637: 
1.220     brouard  10638:   for (i=1;i<=imx ; i++) {
1.126     brouard  10639:     sump=sump+weight[i];
                   10640:     /*    sump=sump+1;*/
                   10641:     num=num+1;
                   10642:   }
1.302     brouard  10643:   L=0.0;
                   10644:   /* agegomp=AGEGOMP; */
1.126     brouard  10645:   /* for (i=0; i<=imx; i++) 
                   10646:      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]);*/
                   10647: 
1.302     brouard  10648:   for (i=1;i<=imx ; i++) {
                   10649:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10650:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10651:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10652:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10653:      * +
                   10654:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10655:      */
                   10656:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10657:        if (cens[i] == 1){
                   10658:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10659:        } else if (cens[i] == 0){
1.126     brouard  10660:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10661:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10662:       } else
                   10663:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10664:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10665:        L=L+A*weight[i];
1.126     brouard  10666:        /*      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  10667:      }
                   10668:   }
1.126     brouard  10669: 
1.302     brouard  10670:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10671:  
                   10672:   return -2*L*num/sump;
                   10673: }
                   10674: 
1.136     brouard  10675: #ifdef GSL
                   10676: /******************* Gompertz_f Likelihood ******************************/
                   10677: double gompertz_f(const gsl_vector *v, void *params)
                   10678: { 
1.302     brouard  10679:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10680:   double *x= (double *) v->data;
                   10681:   int i,n=0; /* n is the size of the sample */
                   10682: 
                   10683:   for (i=0;i<=imx-1 ; i++) {
                   10684:     sump=sump+weight[i];
                   10685:     /*    sump=sump+1;*/
                   10686:     num=num+1;
                   10687:   }
                   10688:  
                   10689:  
                   10690:   /* for (i=0; i<=imx; i++) 
                   10691:      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]);*/
                   10692:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10693:   for (i=1;i<=imx ; i++)
                   10694:     {
                   10695:       if (cens[i] == 1 && wav[i]>1)
                   10696:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10697:       
                   10698:       if (cens[i] == 0 && wav[i]>1)
                   10699:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10700:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10701:       
                   10702:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10703:       if (wav[i] > 1 ) { /* ??? */
                   10704:        LL=LL+A*weight[i];
                   10705:        /*      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]);*/
                   10706:       }
                   10707:     }
                   10708: 
                   10709:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10710:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10711:  
                   10712:   return -2*LL*num/sump;
                   10713: }
                   10714: #endif
                   10715: 
1.126     brouard  10716: /******************* Printing html file ***********/
1.201     brouard  10717: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10718:                  int lastpass, int stepm, int weightopt, char model[],\
                   10719:                  int imx,  double p[],double **matcov,double agemortsup){
                   10720:   int i,k;
                   10721: 
                   10722:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10723:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10724:   for (i=1;i<=2;i++) 
                   10725:     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  10726:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10727:   fprintf(fichtm,"</ul>");
                   10728: 
                   10729: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10730: 
                   10731:  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>");
                   10732: 
                   10733:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10734:    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]);
                   10735: 
                   10736:  
                   10737:   fflush(fichtm);
                   10738: }
                   10739: 
                   10740: /******************* Gnuplot file **************/
1.201     brouard  10741: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10742: 
                   10743:   char dirfileres[132],optfileres[132];
1.164     brouard  10744: 
1.126     brouard  10745:   int ng;
                   10746: 
                   10747: 
                   10748:   /*#ifdef windows */
                   10749:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10750:     /*#endif */
                   10751: 
                   10752: 
                   10753:   strcpy(dirfileres,optionfilefiname);
                   10754:   strcpy(optfileres,"vpl");
1.199     brouard  10755:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10756:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10757:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10758:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10759:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10760: 
                   10761: } 
                   10762: 
1.136     brouard  10763: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10764: {
1.126     brouard  10765: 
1.136     brouard  10766:   /*-------- data file ----------*/
                   10767:   FILE *fic;
                   10768:   char dummy[]="                         ";
1.240     brouard  10769:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10770:   int lstra;
1.136     brouard  10771:   int linei, month, year,iout;
1.302     brouard  10772:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10773:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10774:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10775:   char *stratrunc;
1.223     brouard  10776: 
1.349     brouard  10777:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10778:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10779:   
                   10780:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10781:   
1.136     brouard  10782:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10783:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10784:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10785:   }
1.126     brouard  10786: 
1.302     brouard  10787:     /* Is it a BOM UTF-8 Windows file? */
                   10788:   /* First data line */
                   10789:   linei=0;
                   10790:   while(fgets(line, MAXLINE, fic)) {
                   10791:     noffset=0;
                   10792:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10793:     {
                   10794:       noffset=noffset+3;
                   10795:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10796:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10797:       fflush(ficlog); return 1;
                   10798:     }
                   10799:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10800:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10801:     {
                   10802:       noffset=noffset+2;
1.304     brouard  10803:       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);
                   10804:       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  10805:       fflush(ficlog); return 1;
                   10806:     }
                   10807:     else if( line[0] == 0 && line[1] == 0)
                   10808:     {
                   10809:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10810:        noffset=noffset+4;
1.304     brouard  10811:        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);
                   10812:        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  10813:        fflush(ficlog); return 1;
                   10814:       }
                   10815:     } else{
                   10816:       ;/*printf(" Not a BOM file\n");*/
                   10817:     }
                   10818:         /* If line starts with a # it is a comment */
                   10819:     if (line[noffset] == '#') {
                   10820:       linei=linei+1;
                   10821:       break;
                   10822:     }else{
                   10823:       break;
                   10824:     }
                   10825:   }
                   10826:   fclose(fic);
                   10827:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10828:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10829:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10830:   }
                   10831:   /* Not a Bom file */
                   10832:   
1.136     brouard  10833:   i=1;
                   10834:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10835:     linei=linei+1;
                   10836:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10837:       if(line[j] == '\t')
                   10838:        line[j] = ' ';
                   10839:     }
                   10840:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10841:       ;
                   10842:     };
                   10843:     line[j+1]=0;  /* Trims blanks at end of line */
                   10844:     if(line[0]=='#'){
                   10845:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10846:       printf("Comment line\n%s\n",line);
                   10847:       continue;
                   10848:     }
                   10849:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10850:     strcpy(line, linetmp);
1.223     brouard  10851:     
                   10852:     /* Loops on waves */
                   10853:     for (j=maxwav;j>=1;j--){
                   10854:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10855:        cutv(stra, strb, line, ' '); 
                   10856:        if(strb[0]=='.') { /* Missing value */
                   10857:          lval=-1;
                   10858:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10859:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10860:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10861:            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);
                   10862:            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);
                   10863:            return 1;
                   10864:          }
                   10865:        }else{
                   10866:          errno=0;
                   10867:          /* what_kind_of_number(strb); */
                   10868:          dval=strtod(strb,&endptr); 
                   10869:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10870:          /* if(strb != endptr && *endptr == '\0') */
                   10871:          /*    dval=dlval; */
                   10872:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10873:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10874:            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);
                   10875:            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);
                   10876:            return 1;
                   10877:          }
                   10878:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10879:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10880:        }
                   10881:        strcpy(line,stra);
1.223     brouard  10882:       }/* end loop ntqv */
1.225     brouard  10883:       
1.223     brouard  10884:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10885:        cutv(stra, strb, line, ' '); 
                   10886:        if(strb[0]=='.') { /* Missing value */
                   10887:          lval=-1;
                   10888:        }else{
                   10889:          errno=0;
                   10890:          lval=strtol(strb,&endptr,10); 
                   10891:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10892:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10893:            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);
                   10894:            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);
                   10895:            return 1;
                   10896:          }
                   10897:        }
                   10898:        if(lval <-1 || lval >1){
                   10899:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10900:  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  10901:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10902:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10903:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10904:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10905:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10906:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10907:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10908:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10909:  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  10910:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10911:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10912:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10913:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10914:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10915:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10916:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10917:          return 1;
                   10918:        }
1.341     brouard  10919:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10920:        strcpy(line,stra);
1.223     brouard  10921:       }/* end loop ntv */
1.225     brouard  10922:       
1.223     brouard  10923:       /* Statuses  at wave */
1.137     brouard  10924:       cutv(stra, strb, line, ' '); 
1.223     brouard  10925:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10926:        lval=-1;
1.136     brouard  10927:       }else{
1.238     brouard  10928:        errno=0;
                   10929:        lval=strtol(strb,&endptr,10); 
                   10930:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10931:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10932:          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);
                   10933:          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);
                   10934:          return 1;
                   10935:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10936:          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);
                   10937:          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  10938:          return 1;
                   10939:        }
1.136     brouard  10940:       }
1.225     brouard  10941:       
1.136     brouard  10942:       s[j][i]=lval;
1.225     brouard  10943:       
1.223     brouard  10944:       /* Date of Interview */
1.136     brouard  10945:       strcpy(line,stra);
                   10946:       cutv(stra, strb,line,' ');
1.169     brouard  10947:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10948:       }
1.169     brouard  10949:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10950:        month=99;
                   10951:        year=9999;
1.136     brouard  10952:       }else{
1.225     brouard  10953:        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);
                   10954:        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);
                   10955:        return 1;
1.136     brouard  10956:       }
                   10957:       anint[j][i]= (double) year; 
1.302     brouard  10958:       mint[j][i]= (double)month;
                   10959:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10960:       /*       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]); */
                   10961:       /*       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]); */
                   10962:       /* } */
1.136     brouard  10963:       strcpy(line,stra);
1.223     brouard  10964:     } /* End loop on waves */
1.225     brouard  10965:     
1.223     brouard  10966:     /* Date of death */
1.136     brouard  10967:     cutv(stra, strb,line,' '); 
1.169     brouard  10968:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10969:     }
1.169     brouard  10970:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10971:       month=99;
                   10972:       year=9999;
                   10973:     }else{
1.141     brouard  10974:       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  10975:       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);
                   10976:       return 1;
1.136     brouard  10977:     }
                   10978:     andc[i]=(double) year; 
                   10979:     moisdc[i]=(double) month; 
                   10980:     strcpy(line,stra);
                   10981:     
1.223     brouard  10982:     /* Date of birth */
1.136     brouard  10983:     cutv(stra, strb,line,' '); 
1.169     brouard  10984:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10985:     }
1.169     brouard  10986:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10987:       month=99;
                   10988:       year=9999;
                   10989:     }else{
1.141     brouard  10990:       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);
                   10991:       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  10992:       return 1;
1.136     brouard  10993:     }
                   10994:     if (year==9999) {
1.141     brouard  10995:       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);
                   10996:       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  10997:       return 1;
                   10998:       
1.136     brouard  10999:     }
                   11000:     annais[i]=(double)(year);
1.302     brouard  11001:     moisnais[i]=(double)(month);
                   11002:     for (j=1;j<=maxwav;j++){
                   11003:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   11004:        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]);
                   11005:        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]);
                   11006:       }
                   11007:     }
                   11008: 
1.136     brouard  11009:     strcpy(line,stra);
1.225     brouard  11010:     
1.223     brouard  11011:     /* Sample weight */
1.136     brouard  11012:     cutv(stra, strb,line,' '); 
                   11013:     errno=0;
                   11014:     dval=strtod(strb,&endptr); 
                   11015:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  11016:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   11017:       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  11018:       fflush(ficlog);
                   11019:       return 1;
                   11020:     }
                   11021:     weight[i]=dval; 
                   11022:     strcpy(line,stra);
1.225     brouard  11023:     
1.223     brouard  11024:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11025:       cutv(stra, strb, line, ' '); 
                   11026:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  11027:        lval=-1;
1.311     brouard  11028:        coqvar[iv][i]=NAN; 
                   11029:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11030:       }else{
1.225     brouard  11031:        errno=0;
                   11032:        /* what_kind_of_number(strb); */
                   11033:        dval=strtod(strb,&endptr);
                   11034:        /* if(strb != endptr && *endptr == '\0') */
                   11035:        /*   dval=dlval; */
                   11036:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11037:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11038:          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);
                   11039:          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);
                   11040:          return 1;
                   11041:        }
                   11042:        coqvar[iv][i]=dval; 
1.226     brouard  11043:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11044:       }
                   11045:       strcpy(line,stra);
                   11046:     }/* end loop nqv */
1.136     brouard  11047:     
1.223     brouard  11048:     /* Covariate values */
1.136     brouard  11049:     for (j=ncovcol;j>=1;j--){
                   11050:       cutv(stra, strb,line,' '); 
1.223     brouard  11051:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  11052:        lval=-1;
1.136     brouard  11053:       }else{
1.225     brouard  11054:        errno=0;
                   11055:        lval=strtol(strb,&endptr,10); 
                   11056:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11057:          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);
                   11058:          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);
                   11059:          return 1;
                   11060:        }
1.136     brouard  11061:       }
                   11062:       if(lval <-1 || lval >1){
1.225     brouard  11063:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11064:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11065:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11066:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11067:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11068:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11069:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11070:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11071:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11072:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11073:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11074:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11075:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11076:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11077:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11078:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11079:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11080:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11081:        return 1;
1.136     brouard  11082:       }
                   11083:       covar[j][i]=(double)(lval);
                   11084:       strcpy(line,stra);
                   11085:     }  
                   11086:     lstra=strlen(stra);
1.225     brouard  11087:     
1.136     brouard  11088:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11089:       stratrunc = &(stra[lstra-9]);
                   11090:       num[i]=atol(stratrunc);
                   11091:     }
                   11092:     else
                   11093:       num[i]=atol(stra);
                   11094:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11095:       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;}*/
                   11096:     
                   11097:     i=i+1;
                   11098:   } /* End loop reading  data */
1.225     brouard  11099:   
1.136     brouard  11100:   *imax=i-1; /* Number of individuals */
                   11101:   fclose(fic);
1.225     brouard  11102:   
1.136     brouard  11103:   return (0);
1.164     brouard  11104:   /* endread: */
1.225     brouard  11105:   printf("Exiting readdata: ");
                   11106:   fclose(fic);
                   11107:   return (1);
1.223     brouard  11108: }
1.126     brouard  11109: 
1.234     brouard  11110: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11111:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11112:   while (*p2 == ' ')
1.234     brouard  11113:     p2++; 
                   11114:   /* while ((*p1++ = *p2++) !=0) */
                   11115:   /*   ; */
                   11116:   /* do */
                   11117:   /*   while (*p2 == ' ') */
                   11118:   /*     p2++; */
                   11119:   /* while (*p1++ == *p2++); */
                   11120:   *stri=p2; 
1.145     brouard  11121: }
                   11122: 
1.330     brouard  11123: int decoderesult( char resultline[], int nres)
1.230     brouard  11124: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11125: {
1.235     brouard  11126:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11127:   char resultsav[MAXLINE];
1.330     brouard  11128:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11129:   /* int modelresult[MAXLINE]; */
1.230     brouard  11130:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11131: 
1.234     brouard  11132:   removefirstspace(&resultline);
1.332     brouard  11133:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11134: 
1.332     brouard  11135:   strcpy(resultsav,resultline);
1.342     brouard  11136:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11137:   if (strlen(resultsav) >1){
1.334     brouard  11138:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11139:   }
1.353     brouard  11140:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  11141:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11142:     return (0);
                   11143:   }
1.234     brouard  11144:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  11145:     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, 1+age+%s.\n",j, cptcovs, model);fflush(ficlog);
                   11146:     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, 1+age+%s.\n",j, cptcovs, model);fflush(stdout);
                   11147:     if(j==0)
                   11148:       return 1;
1.234     brouard  11149:   }
1.334     brouard  11150:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11151:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11152:       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  11153:       /* 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  11154:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11155:       /* If a blank, then strc="V4=" and strd='\0' */
                   11156:       if(strc[0]=='\0'){
                   11157:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11158:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11159:        return 1;
                   11160:       }
1.234     brouard  11161:     }else
                   11162:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11163:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11164:     
1.230     brouard  11165:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11166:     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  11167:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11168:     /* cptcovsel++;     */
                   11169:     if (nbocc(stra,'=') >0)
                   11170:       strcpy(resultsav,stra); /* and analyzes it */
                   11171:   }
1.235     brouard  11172:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11173:   /* 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  11174:   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  11175:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11176:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11177:       match=0;
1.318     brouard  11178:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11179:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11180:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11181:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11182:          break;
                   11183:        }
                   11184:       }
                   11185:       if(match == 0){
1.338     brouard  11186:        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]);
                   11187:        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  11188:        return 1;
1.234     brouard  11189:       }
1.332     brouard  11190:     }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*/
                   11191:       /* We feed resultmodel[k1]=k2; */
                   11192:       match=0;
                   11193:       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 */
                   11194:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11195:          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  11196:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11197:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11198:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11199:          break;
                   11200:        }
                   11201:       }
                   11202:       if(match == 0){
1.338     brouard  11203:        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]);
                   11204:        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  11205:       return 1;
                   11206:       }
1.349     brouard  11207:     }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  11208:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11209:       match=0;
1.342     brouard  11210:       /* 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  11211:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11212:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11213:          /* modelresult[k2]=k1; */
1.342     brouard  11214:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11215:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11216:        }
                   11217:       }
                   11218:       if(match == 0){
1.349     brouard  11219:        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);
                   11220:        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  11221:        return 1;
                   11222:       }
                   11223:       match=0;
                   11224:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11225:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11226:          /* modelresult[k2]=k1;*/
1.342     brouard  11227:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11228:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11229:          break;
                   11230:        }
                   11231:       }
                   11232:       if(match == 0){
1.349     brouard  11233:        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);
                   11234:        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  11235:        return 1;
                   11236:       }
                   11237:     }/* End of testing */
1.333     brouard  11238:   }/* End loop cptcovt */
1.235     brouard  11239:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11240:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11241:   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)
                   11242:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11243:     match=0;
1.318     brouard  11244:     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  11245:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11246:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11247:          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  11248:          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  11249:          ++match;
                   11250:        }
                   11251:       }
                   11252:     }
                   11253:     if(match == 0){
1.338     brouard  11254:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11255:       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  11256:       return 1;
1.234     brouard  11257:     }else if(match > 1){
1.338     brouard  11258:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11259:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11260:       return 1;
1.234     brouard  11261:     }
                   11262:   }
1.334     brouard  11263:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11264:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11265:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11266:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11267:   /* 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*/
                   11268:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11269:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11270:   /*    1 0 0 0 */
                   11271:   /*    2 1 0 0 */
                   11272:   /*    3 0 1 0 */ 
1.330     brouard  11273:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11274:   /*    5 0 0 1 */
1.330     brouard  11275:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11276:   /*    7 0 1 1 */
                   11277:   /*    8 1 1 1 */
1.237     brouard  11278:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11279:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11280:   /* V5*age V5 known which value for nres?  */
                   11281:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11282:   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.
                   11283:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11284:     /* k counting number of combination of single dummies in the equation model */
                   11285:     /* k4 counting single dummies in the equation model */
                   11286:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11287:     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  11288:        /* 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  11289:       /* 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  11290:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11291:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11292:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11293:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11294:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11295:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11296:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11297:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11298:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11299:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11300:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11301:       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  11302:       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  11303:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11304:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11305:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11306:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11307:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11308:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11309:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11310:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11311:       /* 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  11312:       k4++;;
1.331     brouard  11313:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11314:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11315:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11316:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11317:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11318:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11319:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11320:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11321:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11322:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11323:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11324:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11325:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11326:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11327:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11328:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11329:       /* 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  11330:       k4q++;;
1.350     brouard  11331:     }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"*/
                   11332:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11333:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  11334:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11335:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11336:       /* 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]]); */
                   11337:       }else{
                   11338:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11339:        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)*/
                   11340:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11341:        precov[nres][k1]=Tvalsel[k3];
                   11342:       }
1.342     brouard  11343:       /* 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  11344:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  11345:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11346:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11347:       /* 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]]); */
                   11348:       }else{
                   11349:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11350:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11351:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11352:        precov[nres][k1]=Tvalsel[k3q];
                   11353:       }
1.342     brouard  11354:       /* 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  11355:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11356:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11357:       /* 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  11358:     }else{
1.332     brouard  11359:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11360:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11361:     }
                   11362:   }
1.234     brouard  11363:   
1.334     brouard  11364:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11365:   return (0);
                   11366: }
1.235     brouard  11367: 
1.230     brouard  11368: int decodemodel( char model[], int lastobs)
                   11369:  /**< This routine decodes the model and returns:
1.224     brouard  11370:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11371:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11372:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11373:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11374:        * - cptcovage number of covariates with age*products =2
                   11375:        * - cptcovs number of simple covariates
1.339     brouard  11376:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11377:        * - 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  11378:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11379:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11380:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11381:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11382:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11383:        */
1.319     brouard  11384: /* 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  11385: {
1.238     brouard  11386:   int i, j, k, ks, v;
1.349     brouard  11387:   int n,m;
                   11388:   int  j1, k1, k11, k12, k2, k3, k4;
                   11389:   char modelsav[300];
                   11390:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11391:   char *strpt;
1.349     brouard  11392:   int  **existcomb;
                   11393:   
                   11394:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11395:   for(i=1;i<=NCOVMAX;i++)
                   11396:     for(j=1;j<=NCOVMAX;j++)
                   11397:       existcomb[i][j]=0;
                   11398:     
1.145     brouard  11399:   /*removespace(model);*/
1.136     brouard  11400:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11401:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11402:     if (strstr(model,"AGE") !=0){
1.192     brouard  11403:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11404:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11405:       return 1;
                   11406:     }
1.141     brouard  11407:     if (strstr(model,"v") !=0){
1.338     brouard  11408:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11409:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11410:       return 1;
                   11411:     }
1.187     brouard  11412:     strcpy(modelsav,model); 
                   11413:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11414:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11415:       if(strpt != model){
1.338     brouard  11416:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11417:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11418:  corresponding column of parameters.\n",model);
1.338     brouard  11419:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11420:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11421:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11422:        return 1;
1.225     brouard  11423:       }
1.187     brouard  11424:       nagesqr=1;
                   11425:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11426:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11427:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11428:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11429:       else 
1.234     brouard  11430:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11431:     }else
                   11432:       nagesqr=0;
1.349     brouard  11433:     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  11434:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11435:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  11436:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  11437:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11438:                     * cst, age and age*age 
                   11439:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11440:       /* including age products which are counted in cptcovage.
                   11441:        * but the covariates which are products must be treated 
                   11442:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11443:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11444:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11445:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11446:       cptcovprodage=0;
                   11447:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11448:       
1.187     brouard  11449:       /*   Design
                   11450:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11451:        *  <          ncovcol=8                >
                   11452:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11453:        *   k=  1    2      3       4     5       6      7        8
                   11454:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11455:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11456:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11457:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11458:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11459:        *  Tage[++cptcovage]=k
1.345     brouard  11460:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11461:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11462:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11463:        *  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
                   11464:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11465:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11466:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11467:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11468:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11469:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11470:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11471:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11472:        * p Tprod[1]@2={                         6, 5}
                   11473:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11474:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11475:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11476:        *How to reorganize? Tvars(orted)
1.187     brouard  11477:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11478:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11479:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11480:        * Struct []
                   11481:        */
1.225     brouard  11482:       
1.187     brouard  11483:       /* This loop fills the array Tvar from the string 'model'.*/
                   11484:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11485:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11486:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11487:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11488:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11489:       /*       k=1 Tvar[1]=2 (from V2) */
                   11490:       /*       k=5 Tvar[5] */
                   11491:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11492:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11493:       /*       } */
1.198     brouard  11494:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11495:       /*
                   11496:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11497:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11498:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11499:       }
1.187     brouard  11500:       cptcovage=0;
1.351     brouard  11501: 
                   11502:       /* First loop in order to calculate */
                   11503:       /* for age*VN*Vm
                   11504:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   11505:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   11506:       */
                   11507:       /* Needs  FixedV[Tvardk[k][1]] */
                   11508:       /* For others:
                   11509:        * Sets  Typevar[k];
                   11510:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11511:        *       Tposprod[k]=k11;
                   11512:        *       Tprod[k11]=k;
                   11513:        *       Tvardk[k][1] =m;
                   11514:        * Needs FixedV[Tvardk[k][1]] == 0
                   11515:       */
                   11516:       
1.319     brouard  11517:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11518:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11519:                                         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" */
                   11520:        if (nbocc(modelsav,'+')==0)
                   11521:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11522:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11523:        /*scanf("%d",i);*/
1.349     brouard  11524:        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 */
                   11525:          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  */
                   11526:          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   */
                   11527:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11528:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11529:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11530:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11531:              /* We want strb=Vn*Vm */
                   11532:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11533:                 strcpy(strb,strd);
                   11534:                 strcat(strb,"*");
                   11535:                 strcat(strb,stre);
                   11536:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11537:                 strcpy(strb,strf);
                   11538:                 strcat(strb,"*");
                   11539:                 strcat(strb,stre);
                   11540:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11541:               }
1.351     brouard  11542:              /* 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]]]); */
                   11543:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  11544:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11545:              strcpy(stre,strb); /* save full b in stre */
                   11546:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11547:              strcpy(strf,strc); /* save short c in new short f */
                   11548:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11549:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11550:             }
                   11551:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11552:             /* 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 *\/ */
                   11553:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11554:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11555:            n=atoi(stre);
1.234     brouard  11556:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11557:            m=atoi(strc);
                   11558:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11559:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11560:            if(existcomb[n][m] == 0){
                   11561:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11562:              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);
                   11563:              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);
                   11564:              fflush(ficlog);
                   11565:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11566:              k12++;
                   11567:              existcomb[n][m]=k1;
                   11568:              existcomb[m][n]=k1;
                   11569:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11570:              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*/
                   11571:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11572:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11573:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11574:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11575:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  11576: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  11577:              if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* If the product is a fixed covariate then we feed the new column with Vn*Vm */
                   11578:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11579:                  /* Computes the new covariate which is a product of
                   11580:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11581:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11582:                }
                   11583:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11584:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11585:                k12++;
                   11586:                FixedV[ncovcolt+k12]=0;
                   11587:              }else{ /*End of FixedV */
                   11588:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11589:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11590:                k12++;
                   11591:                FixedV[ncovcolt+k12]=1;
                   11592:              }
                   11593:            }else{  /* k1 Vn*Vm already exists */
                   11594:              k11=existcomb[n][m];
                   11595:              Tposprod[k]=k11; /* OK */
                   11596:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11597:              Tvardk[k][1]=m;
                   11598:              Tvardk[k][2]=n;
                   11599:              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 */
                   11600:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11601:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11602:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11603:                Tvar[Tage[cptcovage]]=k1;
                   11604:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11605:                k12++;
                   11606:                FixedV[ncovcolt+k12]=0;
                   11607:              }else{ /* Already exists but time varying (and age) */
                   11608:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11609:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11610:                /* Tvar[Tage[cptcovage]]=k1; */
                   11611:                cptcovprodvage++;
                   11612:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11613:                k12++;
                   11614:                FixedV[ncovcolt+k12]=1;
                   11615:              }
                   11616:            }
                   11617:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11618:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11619:          } 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 */
                   11620:             cptcovprod++;
                   11621:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11622:               /* covar is not filled and then is empty */
                   11623:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11624:               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 */
                   11625:               Typevar[k]=1;  /* 1 for age product */
                   11626:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11627:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11628:              if( FixedV[Tvar[k]] == 0){
                   11629:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11630:              }else{
                   11631:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11632:              }
                   11633:               /*printf("stre=%s ", stre);*/
                   11634:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11635:               cutl(stre,strb,strc,'V');
                   11636:               Tvar[k]=atoi(stre);
                   11637:               Typevar[k]=1;  /* 1 for age product */
                   11638:               cptcovage++;
                   11639:               Tage[cptcovage]=k;
                   11640:              if( FixedV[Tvar[k]] == 0){
                   11641:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11642:              }else{
                   11643:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11644:              }
1.349     brouard  11645:             }else{ /*  for product Vn*Vm */
                   11646:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11647:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11648:              n=atoi(stre);
                   11649:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11650:              m=atoi(strc);
                   11651:              k1++;
                   11652:              cptcovprodnoage++;
                   11653:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11654:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11655:                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]);
                   11656:                fflush(ficlog);
                   11657:                k11=existcomb[n][m];
                   11658:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11659:                Tposprod[k]=k11;
                   11660:                Tprod[k11]=k;
                   11661:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11662:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11663:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11664:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11665:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11666:                existcomb[n][m]=k1;
                   11667:                existcomb[m][n]=k1;
                   11668:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11669:                                                    because this model-covariate is a construction we invent a new column
                   11670:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11671:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11672:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11673:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11674:                /* Please remark that the new variables are model dependent */
                   11675:                /* If we have 4 variable but the model uses only 3, like in
                   11676:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11677:                 *  k=     1     2      3   4     5        6        7       8
                   11678:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11679:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11680:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11681:                 */
                   11682:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11683:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11684:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11685:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11686:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11687:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11688:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11689:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11690:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11691:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11692:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11693:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11694:                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 */
                   11695:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11696:                    /* Computes the new covariate which is a product of
                   11697:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11698:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11699:                  }
                   11700:                  /* TvarVV[k2]=n; */
                   11701:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11702:                  /* TvarVV[k2+1]=m; */
                   11703:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11704:                }else{ /* not FixedV */
                   11705:                  /* TvarVV[k2]=n; */
                   11706:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11707:                  /* TvarVV[k2+1]=m; */
                   11708:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11709:                }                 
                   11710:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11711:            } /*  End of product Vn*Vm */
                   11712:           } /* End of age*double product or simple product */
                   11713:        }else { /* not a product */
1.234     brouard  11714:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11715:          /*  scanf("%d",i);*/
                   11716:          cutl(strd,strc,strb,'V');
                   11717:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11718:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11719:          Tvar[k]=atoi(strd);
                   11720:          Typevar[k]=0;  /* 0 for simple covariates */
                   11721:        }
                   11722:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11723:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11724:                                  scanf("%d",i);*/
1.187     brouard  11725:       } /* end of loop + on total covariates */
1.351     brouard  11726: 
                   11727:       
1.187     brouard  11728:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11729:   } /* end if strlen(model == 0) */
1.349     brouard  11730:   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  */
                   11731: 
1.136     brouard  11732:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11733:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11734:   
1.136     brouard  11735:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11736:      printf("cptcovprod=%d ", cptcovprod);
                   11737:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11738:      scanf("%d ",i);*/
                   11739: 
                   11740: 
1.230     brouard  11741: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11742:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11743: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11744:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11745:    k =           1    2   3     4       5       6      7      8        9
                   11746:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11747:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11748:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11749:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11750:          Tmodelind[combination of covar]=k;
1.225     brouard  11751: */  
                   11752: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11753:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11754:   /* 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  11755:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11756:   printf("Model=1+age+%s\n\
1.349     brouard  11757: 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  11758: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11759: 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  11760:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11761: 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  11762: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11763: 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  11764:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11765:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  11766: 
                   11767: 
                   11768:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   11769: 
                   11770:   
1.349     brouard  11771:   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  11772:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11773:       Fixed[k]= 0;
                   11774:       Dummy[k]= 0;
1.225     brouard  11775:       ncoveff++;
1.232     brouard  11776:       ncovf++;
1.234     brouard  11777:       nsd++;
                   11778:       modell[k].maintype= FTYPE;
                   11779:       TvarsD[nsd]=Tvar[k];
                   11780:       TvarsDind[nsd]=k;
1.330     brouard  11781:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11782:       TvarF[ncovf]=Tvar[k];
                   11783:       TvarFind[ncovf]=k;
                   11784:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11785:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11786:     /* }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  11787:     }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  11788:       Fixed[k]= 0;
                   11789:       Dummy[k]= 1;
1.230     brouard  11790:       nqfveff++;
1.234     brouard  11791:       modell[k].maintype= FTYPE;
                   11792:       modell[k].subtype= FQ;
                   11793:       nsq++;
1.334     brouard  11794:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11795:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11796:       ncovf++;
1.234     brouard  11797:       TvarF[ncovf]=Tvar[k];
                   11798:       TvarFind[ncovf]=k;
1.231     brouard  11799:       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  11800:       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  11801:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11802:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11803:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11804:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11805:       ncovvt++;
                   11806:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11807:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11808: 
1.227     brouard  11809:       Fixed[k]= 1;
                   11810:       Dummy[k]= 0;
1.225     brouard  11811:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11812:       modell[k].maintype= VTYPE;
                   11813:       modell[k].subtype= VD;
                   11814:       nsd++;
                   11815:       TvarsD[nsd]=Tvar[k];
                   11816:       TvarsDind[nsd]=k;
1.330     brouard  11817:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11818:       ncovv++; /* Only simple time varying variables */
                   11819:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11820:       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  11821:       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 */
                   11822:       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  11823:       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);
                   11824:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11825:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11826:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11827:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11828:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11829:       ncovvt++;
                   11830:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11831:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11832:       
1.234     brouard  11833:       Fixed[k]= 1;
                   11834:       Dummy[k]= 1;
                   11835:       nqtveff++;
                   11836:       modell[k].maintype= VTYPE;
                   11837:       modell[k].subtype= VQ;
                   11838:       ncovv++; /* Only simple time varying variables */
                   11839:       nsq++;
1.334     brouard  11840:       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) */
                   11841:       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  11842:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11843:       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  11844:       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 */
                   11845:       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  11846:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11847:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11848:       /* 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  11849:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11850:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11851:       ncova++;
                   11852:       TvarA[ncova]=Tvar[k];
                   11853:       TvarAind[ncova]=k;
1.349     brouard  11854:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11855:       /** 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  11856:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11857:        Fixed[k]= 2;
                   11858:        Dummy[k]= 2;
                   11859:        modell[k].maintype= ATYPE;
                   11860:        modell[k].subtype= APFD;
1.349     brouard  11861:        ncovta++;
                   11862:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11863:        TvarAVVAind[ncovta]=k;
1.240     brouard  11864:        /* ncoveff++; */
1.227     brouard  11865:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11866:        Fixed[k]= 2;
                   11867:        Dummy[k]= 3;
                   11868:        modell[k].maintype= ATYPE;
                   11869:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11870:        ncovta++;
                   11871:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11872:        TvarAVVAind[ncovta]=k;
1.240     brouard  11873:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11874:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11875:        Fixed[k]= 3;
                   11876:        Dummy[k]= 2;
                   11877:        modell[k].maintype= ATYPE;
                   11878:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11879:        ncovva++;
                   11880:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11881:        TvarVVAind[ncovva]=k;
                   11882:        ncovta++;
                   11883:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11884:        TvarAVVAind[ncovta]=k;
1.240     brouard  11885:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11886:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11887:        Fixed[k]= 3;
                   11888:        Dummy[k]= 3;
                   11889:        modell[k].maintype= ATYPE;
                   11890:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11891:        ncovva++;
                   11892:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11893:        TvarVVAind[ncovva]=k;
                   11894:        ncovta++;
                   11895:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11896:        TvarAVVAind[ncovta]=k;
1.240     brouard  11897:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11898:       }
1.349     brouard  11899:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11900:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11901:       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 */
                   11902:       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]]);
                   11903:        Fixed[k]= 0;
                   11904:        Dummy[k]= 0;
                   11905:        ncoveff++;
                   11906:        ncovf++;
                   11907:        /* ncovv++; */
                   11908:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11909:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11910:        /* ncovv++; */
                   11911:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11912:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11913:        modell[k].maintype= FTYPE;
                   11914:        TvarF[ncovf]=Tvar[k];
                   11915:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11916:        TvarFind[ncovf]=k;
                   11917:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11918:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11919:       }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  */
                   11920:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11921:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11922:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11923:        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 */
                   11924:        ncovvt++;
                   11925:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11926:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11927:        ncovvt++;
                   11928:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11929:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11930:        
                   11931:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11932:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11933:        
                   11934:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11935:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11936:            Fixed[k]= 1;
                   11937:            Dummy[k]= 0;
                   11938:            modell[k].maintype= FTYPE;
                   11939:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11940:            ncovf++; /* Fixed variables without age */
                   11941:            TvarF[ncovf]=Tvar[k];
                   11942:            TvarFind[ncovf]=k;
                   11943:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11944:            Fixed[k]= 0;  /* Fixed product */
                   11945:            Dummy[k]= 1;
                   11946:            modell[k].maintype= FTYPE;
                   11947:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11948:            ncovf++; /* Varying variables without age */
                   11949:            TvarF[ncovf]=Tvar[k];
                   11950:            TvarFind[ncovf]=k;
                   11951:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11952:            Fixed[k]= 1;
                   11953:            Dummy[k]= 0;
                   11954:            modell[k].maintype= VTYPE;
                   11955:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11956:            ncovv++; /* Varying variables without age */
                   11957:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11958:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11959:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11960:            Fixed[k]= 1;
                   11961:            Dummy[k]= 1;
                   11962:            modell[k].maintype= VTYPE;
                   11963:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11964:            ncovv++; /* Varying variables without age */
                   11965:            TvarV[ncovv]=Tvar[k];
                   11966:            TvarVind[ncovv]=k;
                   11967:          }
                   11968:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11969:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11970:            Fixed[k]= 0;  /*  Fixed product */
                   11971:            Dummy[k]= 1;
                   11972:            modell[k].maintype= FTYPE;
                   11973:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   11974:            ncovf++; /* Fixed variables without age */
                   11975:            TvarF[ncovf]=Tvar[k];
                   11976:            TvarFind[ncovf]=k;
                   11977:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   11978:            Fixed[k]= 1;
                   11979:            Dummy[k]= 1;
                   11980:            modell[k].maintype= VTYPE;
                   11981:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   11982:            ncovv++; /* Varying variables without age */
                   11983:            TvarV[ncovv]=Tvar[k];
                   11984:            TvarVind[ncovv]=k;
                   11985:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   11986:            Fixed[k]= 1;
                   11987:            Dummy[k]= 1;
                   11988:            modell[k].maintype= VTYPE;
                   11989:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   11990:            ncovv++; /* Varying variables without age */
                   11991:            TvarV[ncovv]=Tvar[k];
                   11992:            TvarVind[ncovv]=k;
                   11993:            ncovv++; /* Varying variables without age */
                   11994:            TvarV[ncovv]=Tvar[k];
                   11995:            TvarVind[ncovv]=k;
                   11996:          }
                   11997:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   11998:          if(Tvard[k1][2] <=ncovcol){
                   11999:            Fixed[k]= 1;
                   12000:            Dummy[k]= 1;
                   12001:            modell[k].maintype= VTYPE;
                   12002:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   12003:            ncovv++; /* Varying variables without age */
                   12004:            TvarV[ncovv]=Tvar[k];
                   12005:            TvarVind[ncovv]=k;
                   12006:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12007:            Fixed[k]= 1;
                   12008:            Dummy[k]= 1;
                   12009:            modell[k].maintype= VTYPE;
                   12010:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   12011:            ncovv++; /* Varying variables without age */
                   12012:            TvarV[ncovv]=Tvar[k];
                   12013:            TvarVind[ncovv]=k;
                   12014:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12015:            Fixed[k]= 1;
                   12016:            Dummy[k]= 0;
                   12017:            modell[k].maintype= VTYPE;
                   12018:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12019:            ncovv++; /* Varying variables without age */
                   12020:            TvarV[ncovv]=Tvar[k];
                   12021:            TvarVind[ncovv]=k;
                   12022:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12023:            Fixed[k]= 1;
                   12024:            Dummy[k]= 1;
                   12025:            modell[k].maintype= VTYPE;
                   12026:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12027:            ncovv++; /* Varying variables without age */
                   12028:            TvarV[ncovv]=Tvar[k];
                   12029:            TvarVind[ncovv]=k;
                   12030:          }
                   12031:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12032:          if(Tvard[k1][2] <=ncovcol){
                   12033:            Fixed[k]= 1;
                   12034:            Dummy[k]= 1;
                   12035:            modell[k].maintype= VTYPE;
                   12036:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12037:            ncovv++; /* Varying variables without age */
                   12038:            TvarV[ncovv]=Tvar[k];
                   12039:            TvarVind[ncovv]=k;
                   12040:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12041:            Fixed[k]= 1;
                   12042:            Dummy[k]= 1;
                   12043:            modell[k].maintype= VTYPE;
                   12044:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12045:            ncovv++; /* Varying variables without age */
                   12046:            TvarV[ncovv]=Tvar[k];
                   12047:            TvarVind[ncovv]=k;
                   12048:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12049:            Fixed[k]= 1;
                   12050:            Dummy[k]= 1;
                   12051:            modell[k].maintype= VTYPE;
                   12052:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12053:            ncovv++; /* Varying variables without age */
                   12054:            TvarV[ncovv]=Tvar[k];
                   12055:            TvarVind[ncovv]=k;
                   12056:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12057:            Fixed[k]= 1;
                   12058:            Dummy[k]= 1;
                   12059:            modell[k].maintype= VTYPE;
                   12060:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12061:            ncovv++; /* Varying variables without age */
                   12062:            TvarV[ncovv]=Tvar[k];
                   12063:            TvarVind[ncovv]=k;
                   12064:          }
                   12065:        }else{
                   12066:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12067:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12068:        } /*end k1*/
                   12069:       }
                   12070:     }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  12071:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  12072:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12073:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12074:       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 */
                   12075:       ncova++;
                   12076:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12077:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12078:       ncova++;
                   12079:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12080:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  12081: 
1.349     brouard  12082:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12083:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12084:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12085:        ncovta++;
                   12086:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12087:        TvarAVVAind[ncovta]=k;
                   12088:        ncovta++;
                   12089:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12090:        TvarAVVAind[ncovta]=k;
                   12091:       }else{
                   12092:        ncovva++;  /* HERY  reached */
                   12093:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12094:        TvarVVAind[ncovva]=k;
                   12095:        ncovva++;
                   12096:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12097:        TvarVVAind[ncovva]=k;
                   12098:        ncovta++;
                   12099:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12100:        TvarAVVAind[ncovta]=k;
                   12101:        ncovta++;
                   12102:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12103:        TvarAVVAind[ncovta]=k;
                   12104:       }
1.339     brouard  12105:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12106:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12107:          Fixed[k]= 2;
                   12108:          Dummy[k]= 2;
1.240     brouard  12109:          modell[k].maintype= FTYPE;
                   12110:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12111:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12112:          /* TvarFind[ncova]=k; */
1.339     brouard  12113:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12114:          Fixed[k]= 2;  /* Fixed product */
                   12115:          Dummy[k]= 3;
1.240     brouard  12116:          modell[k].maintype= FTYPE;
                   12117:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12118:          /* TvarF[ncova]=Tvar[k]; */
                   12119:          /* TvarFind[ncova]=k; */
1.339     brouard  12120:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12121:          Fixed[k]= 3;
                   12122:          Dummy[k]= 2;
1.240     brouard  12123:          modell[k].maintype= VTYPE;
                   12124:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12125:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12126:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12127:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12128:          Fixed[k]= 3;
                   12129:          Dummy[k]= 3;
1.240     brouard  12130:          modell[k].maintype= VTYPE;
                   12131:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12132:          /* ncovv++; /\* Varying variables without age *\/ */
                   12133:          /* TvarV[ncovv]=Tvar[k]; */
                   12134:          /* TvarVind[ncovv]=k; */
1.240     brouard  12135:        }
1.339     brouard  12136:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12137:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12138:          Fixed[k]= 2;  /*  Fixed product */
                   12139:          Dummy[k]= 2;
1.240     brouard  12140:          modell[k].maintype= FTYPE;
                   12141:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12142:          /* ncova++; /\* Fixed variables with age *\/ */
                   12143:          /* TvarF[ncovf]=Tvar[k]; */
                   12144:          /* TvarFind[ncovf]=k; */
1.339     brouard  12145:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12146:          Fixed[k]= 2;
                   12147:          Dummy[k]= 3;
1.240     brouard  12148:          modell[k].maintype= VTYPE;
                   12149:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12150:          /* ncova++; /\* Varying variables with age *\/ */
                   12151:          /* TvarV[ncova]=Tvar[k]; */
                   12152:          /* TvarVind[ncova]=k; */
1.339     brouard  12153:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12154:          Fixed[k]= 3;
                   12155:          Dummy[k]= 2;
1.240     brouard  12156:          modell[k].maintype= VTYPE;
                   12157:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12158:          ncova++; /* Varying variables without age */
                   12159:          TvarV[ncova]=Tvar[k];
                   12160:          TvarVind[ncova]=k;
                   12161:          /* ncova++; /\* Varying variables without age *\/ */
                   12162:          /* TvarV[ncova]=Tvar[k]; */
                   12163:          /* TvarVind[ncova]=k; */
1.240     brouard  12164:        }
1.339     brouard  12165:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12166:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12167:          Fixed[k]= 2;
                   12168:          Dummy[k]= 2;
1.240     brouard  12169:          modell[k].maintype= VTYPE;
                   12170:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12171:          /* ncova++; /\* Varying variables with age *\/ */
                   12172:          /* TvarV[ncova]=Tvar[k]; */
                   12173:          /* TvarVind[ncova]=k; */
1.240     brouard  12174:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12175:          Fixed[k]= 2;
                   12176:          Dummy[k]= 3;
1.240     brouard  12177:          modell[k].maintype= VTYPE;
                   12178:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12179:          /* ncova++; /\* Varying variables with age *\/ */
                   12180:          /* TvarV[ncova]=Tvar[k]; */
                   12181:          /* TvarVind[ncova]=k; */
1.240     brouard  12182:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12183:          Fixed[k]= 3;
                   12184:          Dummy[k]= 2;
1.240     brouard  12185:          modell[k].maintype= VTYPE;
                   12186:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  12187:          /* ncova++; /\* Varying variables with age *\/ */
                   12188:          /* TvarV[ncova]=Tvar[k]; */
                   12189:          /* TvarVind[ncova]=k; */
1.240     brouard  12190:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12191:          Fixed[k]= 3;
                   12192:          Dummy[k]= 3;
1.240     brouard  12193:          modell[k].maintype= VTYPE;
                   12194:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12195:          /* ncova++; /\* Varying variables with age *\/ */
                   12196:          /* TvarV[ncova]=Tvar[k]; */
                   12197:          /* TvarVind[ncova]=k; */
1.240     brouard  12198:        }
1.339     brouard  12199:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12200:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12201:          Fixed[k]= 2;
                   12202:          Dummy[k]= 2;
1.240     brouard  12203:          modell[k].maintype= VTYPE;
                   12204:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12205:          /* ncova++; /\* Varying variables with age *\/ */
                   12206:          /* TvarV[ncova]=Tvar[k]; */
                   12207:          /* TvarVind[ncova]=k; */
1.240     brouard  12208:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12209:          Fixed[k]= 2;
                   12210:          Dummy[k]= 3;
1.240     brouard  12211:          modell[k].maintype= VTYPE;
                   12212:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12213:          /* ncova++; /\* Varying variables with age *\/ */
                   12214:          /* TvarV[ncova]=Tvar[k]; */
                   12215:          /* TvarVind[ncova]=k; */
1.240     brouard  12216:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12217:          Fixed[k]= 3;
                   12218:          Dummy[k]= 2;
1.240     brouard  12219:          modell[k].maintype= VTYPE;
                   12220:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12221:          /* ncova++; /\* Varying variables with age *\/ */
                   12222:          /* TvarV[ncova]=Tvar[k]; */
                   12223:          /* TvarVind[ncova]=k; */
1.240     brouard  12224:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12225:          Fixed[k]= 3;
                   12226:          Dummy[k]= 3;
1.240     brouard  12227:          modell[k].maintype= VTYPE;
                   12228:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12229:          /* ncova++; /\* Varying variables with age *\/ */
                   12230:          /* TvarV[ncova]=Tvar[k]; */
                   12231:          /* TvarVind[ncova]=k; */
1.240     brouard  12232:        }
1.227     brouard  12233:       }else{
1.240     brouard  12234:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12235:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12236:       } /*end k1*/
1.349     brouard  12237:     } else{
1.226     brouard  12238:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12239:       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  12240:     }
1.342     brouard  12241:     /* 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]); */
                   12242:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12243:     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]);
                   12244:   }
1.349     brouard  12245:   ncovvta=ncovva;
1.227     brouard  12246:   /* Searching for doublons in the model */
                   12247:   for(k1=1; k1<= cptcovt;k1++){
                   12248:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12249:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12250:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12251:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12252:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12253:            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]);
                   12254:            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  12255:            return(1);
                   12256:          }
                   12257:        }else if (Typevar[k1] ==2){
                   12258:          k3=Tposprod[k1];
                   12259:          k4=Tposprod[k2];
                   12260:          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  12261:            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]]);
                   12262:            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  12263:            return(1);
                   12264:          }
                   12265:        }
1.227     brouard  12266:       }
                   12267:     }
1.225     brouard  12268:   }
                   12269:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12270:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12271:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12272:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12273: 
                   12274:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12275:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12276:   /*endread:*/
1.225     brouard  12277:   printf("Exiting decodemodel: ");
                   12278:   return (1);
1.136     brouard  12279: }
                   12280: 
1.169     brouard  12281: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12282: {/* Check ages at death */
1.136     brouard  12283:   int i, m;
1.218     brouard  12284:   int firstone=0;
                   12285:   
1.136     brouard  12286:   for (i=1; i<=imx; i++) {
                   12287:     for(m=2; (m<= maxwav); m++) {
                   12288:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12289:        anint[m][i]=9999;
1.216     brouard  12290:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12291:          s[m][i]=-1;
1.136     brouard  12292:       }
                   12293:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12294:        *nberr = *nberr + 1;
1.218     brouard  12295:        if(firstone == 0){
                   12296:          firstone=1;
1.260     brouard  12297:        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  12298:        }
1.262     brouard  12299:        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  12300:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12301:       }
                   12302:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12303:        (*nberr)++;
1.259     brouard  12304:        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  12305:        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  12306:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12307:       }
                   12308:     }
                   12309:   }
                   12310: 
                   12311:   for (i=1; i<=imx; i++)  {
                   12312:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12313:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12314:       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  12315:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12316:          if(agedc[i]>0){
                   12317:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12318:              agev[m][i]=agedc[i];
1.214     brouard  12319:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12320:            }else {
1.136     brouard  12321:              if ((int)andc[i]!=9999){
                   12322:                nbwarn++;
                   12323:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12324:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12325:                agev[m][i]=-1;
                   12326:              }
                   12327:            }
1.169     brouard  12328:          } /* agedc > 0 */
1.214     brouard  12329:        } /* end if */
1.136     brouard  12330:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12331:                                 years but with the precision of a month */
                   12332:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12333:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12334:            agev[m][i]=1;
                   12335:          else if(agev[m][i] < *agemin){ 
                   12336:            *agemin=agev[m][i];
                   12337:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12338:          }
                   12339:          else if(agev[m][i] >*agemax){
                   12340:            *agemax=agev[m][i];
1.156     brouard  12341:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12342:          }
                   12343:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12344:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12345:        } /* en if 9*/
1.136     brouard  12346:        else { /* =9 */
1.214     brouard  12347:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12348:          agev[m][i]=1;
                   12349:          s[m][i]=-1;
                   12350:        }
                   12351:       }
1.214     brouard  12352:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12353:        agev[m][i]=1;
1.214     brouard  12354:       else{
                   12355:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12356:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12357:        agev[m][i]=0;
                   12358:       }
                   12359:     } /* End for lastpass */
                   12360:   }
1.136     brouard  12361:     
                   12362:   for (i=1; i<=imx; i++)  {
                   12363:     for(m=firstpass; (m<=lastpass); m++){
                   12364:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12365:        (*nberr)++;
1.136     brouard  12366:        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);     
                   12367:        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);     
                   12368:        return 1;
                   12369:       }
                   12370:     }
                   12371:   }
                   12372: 
                   12373:   /*for (i=1; i<=imx; i++){
                   12374:   for (m=firstpass; (m<lastpass); m++){
                   12375:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12376: }
                   12377: 
                   12378: }*/
                   12379: 
                   12380: 
1.139     brouard  12381:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12382:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12383: 
                   12384:   return (0);
1.164     brouard  12385:  /* endread:*/
1.136     brouard  12386:     printf("Exiting calandcheckages: ");
                   12387:     return (1);
                   12388: }
                   12389: 
1.172     brouard  12390: #if defined(_MSC_VER)
                   12391: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12392: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12393: //#include "stdafx.h"
                   12394: //#include <stdio.h>
                   12395: //#include <tchar.h>
                   12396: //#include <windows.h>
                   12397: //#include <iostream>
                   12398: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12399: 
                   12400: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12401: 
                   12402: BOOL IsWow64()
                   12403: {
                   12404:        BOOL bIsWow64 = FALSE;
                   12405: 
                   12406:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12407:        //  (HANDLE, PBOOL);
                   12408: 
                   12409:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12410: 
                   12411:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12412:        const char funcName[] = "IsWow64Process";
                   12413:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12414:                GetProcAddress(module, funcName);
                   12415: 
                   12416:        if (NULL != fnIsWow64Process)
                   12417:        {
                   12418:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12419:                        &bIsWow64))
                   12420:                        //throw std::exception("Unknown error");
                   12421:                        printf("Unknown error\n");
                   12422:        }
                   12423:        return bIsWow64 != FALSE;
                   12424: }
                   12425: #endif
1.177     brouard  12426: 
1.191     brouard  12427: void syscompilerinfo(int logged)
1.292     brouard  12428: {
                   12429: #include <stdint.h>
                   12430: 
                   12431:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12432:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12433:    /* /GS /W3 /Gy
                   12434:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12435:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12436:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12437:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12438:    */ 
                   12439:    /* 64 bits */
1.185     brouard  12440:    /*
                   12441:      /GS /W3 /Gy
                   12442:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12443:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12444:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12445:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12446:    /* Optimization are useless and O3 is slower than O2 */
                   12447:    /*
                   12448:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12449:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12450:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12451:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12452:    */
1.186     brouard  12453:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12454:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12455:       /PDB:"visual studio
                   12456:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12457:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12458:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12459:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12460:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12461:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12462:       uiAccess='false'"
                   12463:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12464:       /NOLOGO /TLBID:1
                   12465:    */
1.292     brouard  12466: 
                   12467: 
1.177     brouard  12468: #if defined __INTEL_COMPILER
1.178     brouard  12469: #if defined(__GNUC__)
                   12470:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12471: #endif
1.177     brouard  12472: #elif defined(__GNUC__) 
1.179     brouard  12473: #ifndef  __APPLE__
1.174     brouard  12474: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12475: #endif
1.177     brouard  12476:    struct utsname sysInfo;
1.178     brouard  12477:    int cross = CROSS;
                   12478:    if (cross){
                   12479:           printf("Cross-");
1.191     brouard  12480:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12481:    }
1.174     brouard  12482: #endif
                   12483: 
1.191     brouard  12484:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12485: #if defined(__clang__)
1.191     brouard  12486:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12487: #endif
                   12488: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12489:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12490: #endif
                   12491: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12492:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12493: #endif
                   12494: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12495:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12496: #endif
                   12497: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12498:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12499: #endif
                   12500: #if defined(_MSC_VER)
1.191     brouard  12501:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12502: #endif
                   12503: #if defined(__PGI)
1.191     brouard  12504:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12505: #endif
                   12506: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12507:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12508: #endif
1.191     brouard  12509:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12510:    
1.167     brouard  12511: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12512: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12513:     // Windows (x64 and x86)
1.191     brouard  12514:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12515: #elif __unix__ // all unices, not all compilers
                   12516:     // Unix
1.191     brouard  12517:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12518: #elif __linux__
                   12519:     // linux
1.191     brouard  12520:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12521: #elif __APPLE__
1.174     brouard  12522:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12523:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12524: #endif
                   12525: 
                   12526: /*  __MINGW32__          */
                   12527: /*  __CYGWIN__  */
                   12528: /* __MINGW64__  */
                   12529: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12530: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12531: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12532: /* _WIN64  // Defined for applications for Win64. */
                   12533: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12534: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12535: 
1.167     brouard  12536: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12537:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12538: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12539:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12540: #else
1.191     brouard  12541:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12542: #endif
                   12543: 
1.169     brouard  12544: #if defined(__GNUC__)
                   12545: # if defined(__GNUC_PATCHLEVEL__)
                   12546: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12547:                             + __GNUC_MINOR__ * 100 \
                   12548:                             + __GNUC_PATCHLEVEL__)
                   12549: # else
                   12550: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12551:                             + __GNUC_MINOR__ * 100)
                   12552: # endif
1.174     brouard  12553:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12554:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12555: 
                   12556:    if (uname(&sysInfo) != -1) {
                   12557:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12558:         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  12559:    }
                   12560:    else
                   12561:       perror("uname() error");
1.179     brouard  12562:    //#ifndef __INTEL_COMPILER 
                   12563: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12564:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12565:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12566: #endif
1.169     brouard  12567: #endif
1.172     brouard  12568: 
1.286     brouard  12569:    //   void main ()
1.172     brouard  12570:    //   {
1.169     brouard  12571: #if defined(_MSC_VER)
1.174     brouard  12572:    if (IsWow64()){
1.191     brouard  12573:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12574:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12575:    }
                   12576:    else{
1.191     brouard  12577:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12578:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12579:    }
1.172     brouard  12580:    //     printf("\nPress Enter to continue...");
                   12581:    //     getchar();
                   12582:    //   }
                   12583: 
1.169     brouard  12584: #endif
                   12585:    
1.167     brouard  12586: 
1.219     brouard  12587: }
1.136     brouard  12588: 
1.219     brouard  12589: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12590:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12591:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12592:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12593:   /* double ftolpl = 1.e-10; */
1.180     brouard  12594:   double age, agebase, agelim;
1.203     brouard  12595:   double tot;
1.180     brouard  12596: 
1.202     brouard  12597:   strcpy(filerespl,"PL_");
                   12598:   strcat(filerespl,fileresu);
                   12599:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12600:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12601:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12602:   }
1.288     brouard  12603:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12604:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12605:   pstamp(ficrespl);
1.288     brouard  12606:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12607:   fprintf(ficrespl,"#Age ");
                   12608:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12609:   fprintf(ficrespl,"\n");
1.180     brouard  12610:   
1.219     brouard  12611:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12612: 
1.219     brouard  12613:   agebase=ageminpar;
                   12614:   agelim=agemaxpar;
1.180     brouard  12615: 
1.227     brouard  12616:   /* i1=pow(2,ncoveff); */
1.234     brouard  12617:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12618:   if (cptcovn < 1){i1=1;}
1.180     brouard  12619: 
1.337     brouard  12620:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12621:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12622:       k=TKresult[nres];
1.338     brouard  12623:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12624:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12625:       /*       continue; */
1.235     brouard  12626: 
1.238     brouard  12627:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12628:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12629:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12630:       /* k=k+1; */
                   12631:       /* to clean */
1.332     brouard  12632:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12633:       fprintf(ficrespl,"#******");
                   12634:       printf("#******");
                   12635:       fprintf(ficlog,"#******");
1.337     brouard  12636:       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  12637:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12638:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12639:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12640:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12641:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12642:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12643:       }
                   12644:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12645:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12646:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12647:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12648:       /* } */
1.238     brouard  12649:       fprintf(ficrespl,"******\n");
                   12650:       printf("******\n");
                   12651:       fprintf(ficlog,"******\n");
                   12652:       if(invalidvarcomb[k]){
                   12653:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12654:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12655:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12656:        continue;
                   12657:       }
1.219     brouard  12658: 
1.238     brouard  12659:       fprintf(ficrespl,"#Age ");
1.337     brouard  12660:       /* for(j=1;j<=cptcoveff;j++) { */
                   12661:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12662:       /* } */
                   12663:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12664:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12665:       }
                   12666:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12667:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12668:     
1.238     brouard  12669:       for (age=agebase; age<=agelim; age++){
                   12670:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12671:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12672:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12673:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12674:        /* for(j=1;j<=cptcoveff;j++) */
                   12675:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12676:        for(j=1;j<=cptcovs;j++)
                   12677:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12678:        tot=0.;
                   12679:        for(i=1; i<=nlstate;i++){
                   12680:          tot +=  prlim[i][i];
                   12681:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12682:        }
                   12683:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12684:       } /* Age */
                   12685:       /* was end of cptcod */
1.337     brouard  12686:     } /* nres */
                   12687:   /* } /\* for each combination *\/ */
1.219     brouard  12688:   return 0;
1.180     brouard  12689: }
                   12690: 
1.218     brouard  12691: 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  12692:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12693:        
                   12694:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12695:    * at any age between ageminpar and agemaxpar
                   12696:         */
1.235     brouard  12697:   int i, j, k, i1, nres=0 ;
1.217     brouard  12698:   /* double ftolpl = 1.e-10; */
                   12699:   double age, agebase, agelim;
                   12700:   double tot;
1.218     brouard  12701:   /* double ***mobaverage; */
                   12702:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12703: 
                   12704:   strcpy(fileresplb,"PLB_");
                   12705:   strcat(fileresplb,fileresu);
                   12706:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12707:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12708:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12709:   }
1.288     brouard  12710:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12711:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12712:   pstamp(ficresplb);
1.288     brouard  12713:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12714:   fprintf(ficresplb,"#Age ");
                   12715:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12716:   fprintf(ficresplb,"\n");
                   12717:   
1.218     brouard  12718:   
                   12719:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12720:   
                   12721:   agebase=ageminpar;
                   12722:   agelim=agemaxpar;
                   12723:   
                   12724:   
1.227     brouard  12725:   i1=pow(2,cptcoveff);
1.218     brouard  12726:   if (cptcovn < 1){i1=1;}
1.227     brouard  12727:   
1.238     brouard  12728:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12729:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12730:       k=TKresult[nres];
                   12731:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12732:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12733:      /*        continue; */
                   12734:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12735:       fprintf(ficresplb,"#******");
                   12736:       printf("#******");
                   12737:       fprintf(ficlog,"#******");
1.338     brouard  12738:       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) */
                   12739:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12740:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12741:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12742:       }
1.338     brouard  12743:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12744:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12745:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12746:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12747:       /* } */
                   12748:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12749:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12750:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12751:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12752:       /* } */
1.238     brouard  12753:       fprintf(ficresplb,"******\n");
                   12754:       printf("******\n");
                   12755:       fprintf(ficlog,"******\n");
                   12756:       if(invalidvarcomb[k]){
                   12757:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12758:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12759:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12760:        continue;
                   12761:       }
1.218     brouard  12762:     
1.238     brouard  12763:       fprintf(ficresplb,"#Age ");
1.338     brouard  12764:       for(j=1;j<=cptcovs;j++) {
                   12765:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12766:       }
                   12767:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12768:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12769:     
                   12770:     
1.238     brouard  12771:       for (age=agebase; age<=agelim; age++){
                   12772:        /* for (age=agebase; age<=agebase; age++){ */
                   12773:        if(mobilavproj > 0){
                   12774:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12775:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12776:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12777:        }else if (mobilavproj == 0){
                   12778:          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);
                   12779:          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);
                   12780:          exit(1);
                   12781:        }else{
                   12782:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12783:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12784:          /* printf("TOTOT\n"); */
                   12785:           /* exit(1); */
1.238     brouard  12786:        }
                   12787:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12788:        for(j=1;j<=cptcovs;j++)
                   12789:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12790:        tot=0.;
                   12791:        for(i=1; i<=nlstate;i++){
                   12792:          tot +=  bprlim[i][i];
                   12793:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12794:        }
                   12795:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12796:       } /* Age */
                   12797:       /* was end of cptcod */
1.255     brouard  12798:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12799:     /* } /\* end of any combination *\/ */
1.238     brouard  12800:   } /* end of nres */  
1.218     brouard  12801:   /* hBijx(p, bage, fage); */
                   12802:   /* fclose(ficrespijb); */
                   12803:   
                   12804:   return 0;
1.217     brouard  12805: }
1.218     brouard  12806:  
1.180     brouard  12807: int hPijx(double *p, int bage, int fage){
                   12808:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12809:   /* to be optimized with precov */
1.180     brouard  12810:   int stepsize;
                   12811:   int agelim;
                   12812:   int hstepm;
                   12813:   int nhstepm;
1.235     brouard  12814:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12815: 
                   12816:   double agedeb;
                   12817:   double ***p3mat;
                   12818: 
1.337     brouard  12819:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12820:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12821:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12822:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12823:   }
                   12824:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12825:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12826:   
                   12827:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12828:   /*if (stepm<=24) stepsize=2;*/
                   12829:   
                   12830:   agelim=AGESUP;
                   12831:   hstepm=stepsize*YEARM; /* Every year of age */
                   12832:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12833:   
                   12834:   /* hstepm=1;   aff par mois*/
                   12835:   pstamp(ficrespij);
                   12836:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12837:   i1= pow(2,cptcoveff);
                   12838:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12839:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12840:   /*   k=k+1;  */
                   12841:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12842:     k=TKresult[nres];
1.338     brouard  12843:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12844:     /* for(k=1; k<=i1;k++){ */
                   12845:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12846:     /*         continue; */
                   12847:     fprintf(ficrespij,"\n#****** ");
                   12848:     for(j=1;j<=cptcovs;j++){
                   12849:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12850:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12851:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12852:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12853:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12854:     }
                   12855:     fprintf(ficrespij,"******\n");
                   12856:     
                   12857:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12858:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12859:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12860:       
                   12861:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12862:       
                   12863:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12864:       oldm=oldms;savm=savms;
                   12865:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12866:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12867:       for(i=1; i<=nlstate;i++)
                   12868:        for(j=1; j<=nlstate+ndeath;j++)
                   12869:          fprintf(ficrespij," %1d-%1d",i,j);
                   12870:       fprintf(ficrespij,"\n");
                   12871:       for (h=0; h<=nhstepm; h++){
                   12872:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12873:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12874:        for(i=1; i<=nlstate;i++)
                   12875:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12876:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12877:        fprintf(ficrespij,"\n");
                   12878:       }
1.337     brouard  12879:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12880:       fprintf(ficrespij,"\n");
1.180     brouard  12881:     }
1.337     brouard  12882:   }
                   12883:   /*}*/
                   12884:   return 0;
1.180     brouard  12885: }
1.218     brouard  12886:  
                   12887:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12888:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12889:     /* To be optimized with precov */
1.217     brouard  12890:   int stepsize;
1.218     brouard  12891:   /* int agelim; */
                   12892:        int ageminl;
1.217     brouard  12893:   int hstepm;
                   12894:   int nhstepm;
1.238     brouard  12895:   int h, i, i1, j, k, nres;
1.218     brouard  12896:        
1.217     brouard  12897:   double agedeb;
                   12898:   double ***p3mat;
1.218     brouard  12899:        
                   12900:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12901:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12902:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12903:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12904:   }
                   12905:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12906:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12907:   
                   12908:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12909:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12910:   
1.218     brouard  12911:   /* agelim=AGESUP; */
1.289     brouard  12912:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12913:   hstepm=stepsize*YEARM; /* Every year of age */
                   12914:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12915:   
                   12916:   /* hstepm=1;   aff par mois*/
                   12917:   pstamp(ficrespijb);
1.255     brouard  12918:   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  12919:   i1= pow(2,cptcoveff);
1.218     brouard  12920:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12921:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12922:   /*   k=k+1;  */
1.238     brouard  12923:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12924:     k=TKresult[nres];
1.338     brouard  12925:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12926:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12927:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12928:     /*         continue; */
                   12929:     fprintf(ficrespijb,"\n#****** ");
                   12930:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12931:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12932:       /* for(j=1;j<=cptcoveff;j++) */
                   12933:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12934:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12935:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12936:     }
                   12937:     fprintf(ficrespijb,"******\n");
                   12938:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12939:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12940:       continue;
                   12941:     }
                   12942:     
                   12943:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12944:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12945:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12946:       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 */
                   12947:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12948:       
                   12949:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12950:       
                   12951:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12952:       /* and memory limitations if stepm is small */
                   12953:       
                   12954:       /* oldm=oldms;savm=savms; */
                   12955:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12956:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12957:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12958:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12959:       for(i=1; i<=nlstate;i++)
                   12960:        for(j=1; j<=nlstate+ndeath;j++)
                   12961:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12962:       fprintf(ficrespijb,"\n");
                   12963:       for (h=0; h<=nhstepm; h++){
                   12964:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12965:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12966:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12967:        for(i=1; i<=nlstate;i++)
                   12968:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12969:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12970:        fprintf(ficrespijb,"\n");
1.337     brouard  12971:       }
                   12972:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12973:       fprintf(ficrespijb,"\n");
                   12974:     } /* end age deb */
                   12975:     /* } /\* end combination *\/ */
1.238     brouard  12976:   } /* end nres */
1.218     brouard  12977:   return 0;
                   12978:  } /*  hBijx */
1.217     brouard  12979: 
1.180     brouard  12980: 
1.136     brouard  12981: /***********************************************/
                   12982: /**************** Main Program *****************/
                   12983: /***********************************************/
                   12984: 
                   12985: int main(int argc, char *argv[])
                   12986: {
                   12987: #ifdef GSL
                   12988:   const gsl_multimin_fminimizer_type *T;
                   12989:   size_t iteri = 0, it;
                   12990:   int rval = GSL_CONTINUE;
                   12991:   int status = GSL_SUCCESS;
                   12992:   double ssval;
                   12993: #endif
                   12994:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12995:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12996:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12997:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12998:   int jj, ll, li, lj, lk;
1.136     brouard  12999:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  13000:   int num_filled;
1.136     brouard  13001:   int itimes;
                   13002:   int NDIM=2;
                   13003:   int vpopbased=0;
1.235     brouard  13004:   int nres=0;
1.258     brouard  13005:   int endishere=0;
1.277     brouard  13006:   int noffset=0;
1.274     brouard  13007:   int ncurrv=0; /* Temporary variable */
                   13008:   
1.164     brouard  13009:   char ca[32], cb[32];
1.136     brouard  13010:   /*  FILE *fichtm; *//* Html File */
                   13011:   /* FILE *ficgp;*/ /*Gnuplot File */
                   13012:   struct stat info;
1.191     brouard  13013:   double agedeb=0.;
1.194     brouard  13014: 
                   13015:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  13016:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  13017: 
1.165     brouard  13018:   double fret;
1.191     brouard  13019:   double dum=0.; /* Dummy variable */
1.136     brouard  13020:   double ***p3mat;
1.218     brouard  13021:   /* double ***mobaverage; */
1.319     brouard  13022:   double wald;
1.164     brouard  13023: 
1.351     brouard  13024:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  13025:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13026: 
1.234     brouard  13027:   char  modeltemp[MAXLINE];
1.332     brouard  13028:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  13029:   
1.136     brouard  13030:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  13031:   char *tok, *val; /* pathtot */
1.334     brouard  13032:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  13033:   int c,  h , cpt, c2;
1.191     brouard  13034:   int jl=0;
                   13035:   int i1, j1, jk, stepsize=0;
1.194     brouard  13036:   int count=0;
                   13037: 
1.164     brouard  13038:   int *tab; 
1.136     brouard  13039:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  13040:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13041:   /* double anprojf, mprojf, jprojf; */
                   13042:   /* double jintmean,mintmean,aintmean;   */
                   13043:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13044:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13045:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13046:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13047:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  13048:   int mobilav=0,popforecast=0;
1.191     brouard  13049:   int hstepm=0, nhstepm=0;
1.136     brouard  13050:   int agemortsup;
                   13051:   float  sumlpop=0.;
                   13052:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13053:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13054: 
1.191     brouard  13055:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  13056:   double ftolpl=FTOL;
                   13057:   double **prlim;
1.217     brouard  13058:   double **bprlim;
1.317     brouard  13059:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13060:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  13061:   double ***paramstart; /* Matrix of starting parameter values */
                   13062:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  13063:   double **matcov; /* Matrix of covariance */
1.203     brouard  13064:   double **hess; /* Hessian matrix */
1.136     brouard  13065:   double ***delti3; /* Scale */
                   13066:   double *delti; /* Scale */
                   13067:   double ***eij, ***vareij;
                   13068:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  13069: 
1.136     brouard  13070:   double *epj, vepp;
1.164     brouard  13071: 
1.273     brouard  13072:   double dateprev1, dateprev2;
1.296     brouard  13073:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13074:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13075: 
1.217     brouard  13076: 
1.136     brouard  13077:   double **ximort;
1.145     brouard  13078:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  13079:   int *dcwave;
                   13080: 
1.164     brouard  13081:   char z[1]="c";
1.136     brouard  13082: 
                   13083:   /*char  *strt;*/
                   13084:   char strtend[80];
1.126     brouard  13085: 
1.164     brouard  13086: 
1.126     brouard  13087: /*   setlocale (LC_ALL, ""); */
                   13088: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13089: /*   textdomain (PACKAGE); */
                   13090: /*   setlocale (LC_CTYPE, ""); */
                   13091: /*   setlocale (LC_MESSAGES, ""); */
                   13092: 
                   13093:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13094:   rstart_time = time(NULL);  
                   13095:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13096:   start_time = *localtime(&rstart_time);
1.126     brouard  13097:   curr_time=start_time;
1.157     brouard  13098:   /*tml = *localtime(&start_time.tm_sec);*/
                   13099:   /* strcpy(strstart,asctime(&tml)); */
                   13100:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13101: 
                   13102: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13103: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13104: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13105: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13106: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13107: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13108: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13109: /*   strt=asctime(&tmg); */
                   13110: /*   printf("Time(after) =%s",strstart);  */
                   13111: /*  (void) time (&time_value);
                   13112: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13113: *  tm = *localtime(&time_value);
                   13114: *  strstart=asctime(&tm);
                   13115: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13116: */
                   13117: 
                   13118:   nberr=0; /* Number of errors and warnings */
                   13119:   nbwarn=0;
1.184     brouard  13120: #ifdef WIN32
                   13121:   _getcwd(pathcd, size);
                   13122: #else
1.126     brouard  13123:   getcwd(pathcd, size);
1.184     brouard  13124: #endif
1.191     brouard  13125:   syscompilerinfo(0);
1.196     brouard  13126:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13127:   if(argc <=1){
                   13128:     printf("\nEnter the parameter file name: ");
1.205     brouard  13129:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13130:       printf("ERROR Empty parameter file name\n");
                   13131:       goto end;
                   13132:     }
1.126     brouard  13133:     i=strlen(pathr);
                   13134:     if(pathr[i-1]=='\n')
                   13135:       pathr[i-1]='\0';
1.156     brouard  13136:     i=strlen(pathr);
1.205     brouard  13137:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13138:       pathr[i-1]='\0';
1.205     brouard  13139:     }
                   13140:     i=strlen(pathr);
                   13141:     if( i==0 ){
                   13142:       printf("ERROR Empty parameter file name\n");
                   13143:       goto end;
                   13144:     }
                   13145:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13146:       printf("Pathr |%s|\n",pathr);
                   13147:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13148:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13149:       strcpy (pathtot, val);
                   13150:       if(pathr[0] == '\0') break; /* Dirty */
                   13151:     }
                   13152:   }
1.281     brouard  13153:   else if (argc<=2){
                   13154:     strcpy(pathtot,argv[1]);
                   13155:   }
1.126     brouard  13156:   else{
                   13157:     strcpy(pathtot,argv[1]);
1.281     brouard  13158:     strcpy(z,argv[2]);
                   13159:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13160:   }
                   13161:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13162:   /*cygwin_split_path(pathtot,path,optionfile);
                   13163:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13164:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13165: 
                   13166:   /* Split argv[0], imach program to get pathimach */
                   13167:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13168:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13169:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13170:  /*   strcpy(pathimach,argv[0]); */
                   13171:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13172:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13173:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13174: #ifdef WIN32
                   13175:   _chdir(path); /* Can be a relative path */
                   13176:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13177: #else
1.126     brouard  13178:   chdir(path); /* Can be a relative path */
1.184     brouard  13179:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13180: #endif
                   13181:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13182:   strcpy(command,"mkdir ");
                   13183:   strcat(command,optionfilefiname);
                   13184:   if((outcmd=system(command)) != 0){
1.169     brouard  13185:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13186:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13187:     /* fclose(ficlog); */
                   13188: /*     exit(1); */
                   13189:   }
                   13190: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13191: /*     perror("mkdir"); */
                   13192: /*   } */
                   13193: 
                   13194:   /*-------- arguments in the command line --------*/
                   13195: 
1.186     brouard  13196:   /* Main Log file */
1.126     brouard  13197:   strcat(filelog, optionfilefiname);
                   13198:   strcat(filelog,".log");    /* */
                   13199:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13200:     printf("Problem with logfile %s\n",filelog);
                   13201:     goto end;
                   13202:   }
                   13203:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13204:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13205:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13206:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13207:  path=%s \n\
                   13208:  optionfile=%s\n\
                   13209:  optionfilext=%s\n\
1.156     brouard  13210:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13211: 
1.197     brouard  13212:   syscompilerinfo(1);
1.167     brouard  13213: 
1.126     brouard  13214:   printf("Local time (at start):%s",strstart);
                   13215:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13216:   fflush(ficlog);
                   13217: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13218: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13219: 
                   13220:   /* */
                   13221:   strcpy(fileres,"r");
                   13222:   strcat(fileres, optionfilefiname);
1.201     brouard  13223:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13224:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13225:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13226: 
1.186     brouard  13227:   /* Main ---------arguments file --------*/
1.126     brouard  13228: 
                   13229:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13230:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13231:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13232:     fflush(ficlog);
1.149     brouard  13233:     /* goto end; */
                   13234:     exit(70); 
1.126     brouard  13235:   }
                   13236: 
                   13237:   strcpy(filereso,"o");
1.201     brouard  13238:   strcat(filereso,fileresu);
1.126     brouard  13239:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13240:     printf("Problem with Output resultfile: %s\n", filereso);
                   13241:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13242:     fflush(ficlog);
                   13243:     goto end;
                   13244:   }
1.278     brouard  13245:       /*-------- Rewriting parameter file ----------*/
                   13246:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13247:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13248:   strcat(rfileres,".");    /* */
                   13249:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13250:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13251:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13252:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13253:     fflush(ficlog);
                   13254:     goto end;
                   13255:   }
                   13256:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13257: 
1.278     brouard  13258:                                      
1.126     brouard  13259:   /* Reads comments: lines beginning with '#' */
                   13260:   numlinepar=0;
1.277     brouard  13261:   /* Is it a BOM UTF-8 Windows file? */
                   13262:   /* First parameter line */
1.197     brouard  13263:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13264:     noffset=0;
                   13265:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13266:     {
                   13267:       noffset=noffset+3;
                   13268:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13269:     }
1.302     brouard  13270: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13271:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13272:     {
                   13273:       noffset=noffset+2;
                   13274:       printf("# File is an UTF16BE BOM file\n");
                   13275:     }
                   13276:     else if( line[0] == 0 && line[1] == 0)
                   13277:     {
                   13278:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13279:        noffset=noffset+4;
                   13280:        printf("# File is an UTF16BE BOM file\n");
                   13281:       }
                   13282:     } else{
                   13283:       ;/*printf(" Not a BOM file\n");*/
                   13284:     }
                   13285:   
1.197     brouard  13286:     /* If line starts with a # it is a comment */
1.277     brouard  13287:     if (line[noffset] == '#') {
1.197     brouard  13288:       numlinepar++;
                   13289:       fputs(line,stdout);
                   13290:       fputs(line,ficparo);
1.278     brouard  13291:       fputs(line,ficres);
1.197     brouard  13292:       fputs(line,ficlog);
                   13293:       continue;
                   13294:     }else
                   13295:       break;
                   13296:   }
                   13297:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13298:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13299:     if (num_filled != 5) {
                   13300:       printf("Should be 5 parameters\n");
1.283     brouard  13301:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13302:     }
1.126     brouard  13303:     numlinepar++;
1.197     brouard  13304:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13305:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13306:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13307:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13308:   }
                   13309:   /* Second parameter line */
                   13310:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13311:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13312:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13313:     if (line[0] == '#') {
                   13314:       numlinepar++;
1.283     brouard  13315:       printf("%s",line);
                   13316:       fprintf(ficres,"%s",line);
                   13317:       fprintf(ficparo,"%s",line);
                   13318:       fprintf(ficlog,"%s",line);
1.197     brouard  13319:       continue;
                   13320:     }else
                   13321:       break;
                   13322:   }
1.223     brouard  13323:   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", \
                   13324:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13325:     if (num_filled != 11) {
                   13326:       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  13327:       printf("but line=%s\n",line);
1.283     brouard  13328:       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");
                   13329:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13330:     }
1.286     brouard  13331:     if( lastpass > maxwav){
                   13332:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13333:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13334:       fflush(ficlog);
                   13335:       goto end;
                   13336:     }
                   13337:       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  13338:     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  13339:     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  13340:     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  13341:   }
1.203     brouard  13342:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13343:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13344:   /* Third parameter line */
                   13345:   while(fgets(line, MAXLINE, ficpar)) {
                   13346:     /* If line starts with a # it is a comment */
                   13347:     if (line[0] == '#') {
                   13348:       numlinepar++;
1.283     brouard  13349:       printf("%s",line);
                   13350:       fprintf(ficres,"%s",line);
                   13351:       fprintf(ficparo,"%s",line);
                   13352:       fprintf(ficlog,"%s",line);
1.197     brouard  13353:       continue;
                   13354:     }else
                   13355:       break;
                   13356:   }
1.351     brouard  13357:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   13358:     if (num_filled != 1){
                   13359:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13360:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13361:       model[0]='\0';
                   13362:       goto end;
                   13363:     }else{
                   13364:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   13365:       strcpy(line, linetmp);
                   13366:     }
                   13367:   }
                   13368:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  13369:     if (num_filled != 1){
1.302     brouard  13370:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13371:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13372:       model[0]='\0';
                   13373:       goto end;
                   13374:     }
                   13375:     else{
                   13376:       if (model[0]=='+'){
                   13377:        for(i=1; i<=strlen(model);i++)
                   13378:          modeltemp[i-1]=model[i];
1.201     brouard  13379:        strcpy(model,modeltemp); 
1.197     brouard  13380:       }
                   13381:     }
1.338     brouard  13382:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13383:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13384:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13385:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13386:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13387:   }
                   13388:   /* 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); */
                   13389:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13390:   /* 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  13391:   /* 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); */
                   13392:   /* 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  13393:   fflush(ficlog);
1.190     brouard  13394:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13395:   if(model[0]=='#'){
1.279     brouard  13396:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13397:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13398:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13399:     if(mle != -1){
1.279     brouard  13400:       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  13401:       exit(1);
                   13402:     }
                   13403:   }
1.126     brouard  13404:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13405:     ungetc(c,ficpar);
                   13406:     fgets(line, MAXLINE, ficpar);
                   13407:     numlinepar++;
1.195     brouard  13408:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13409:       z[0]=line[1];
1.342     brouard  13410:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13411:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13412:     }
                   13413:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13414:     fputs(line, stdout);
                   13415:     //puts(line);
1.126     brouard  13416:     fputs(line,ficparo);
                   13417:     fputs(line,ficlog);
                   13418:   }
                   13419:   ungetc(c,ficpar);
                   13420: 
                   13421:    
1.290     brouard  13422:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13423:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13424:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13425:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13426:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13427:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13428:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13429:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13430:   */
                   13431:   if (strlen(model)>1) 
1.187     brouard  13432:     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  13433:   else
1.187     brouard  13434:     ncovmodel=2; /* Constant and age */
1.133     brouard  13435:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13436:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13437:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13438:     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);
                   13439:     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);
                   13440:     fflush(stdout);
                   13441:     fclose (ficlog);
                   13442:     goto end;
                   13443:   }
1.126     brouard  13444:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13445:   delti=delti3[1][1];
                   13446:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13447:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13448: /* We could also provide initial parameters values giving by simple logistic regression 
                   13449:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13450:       /* for(i=1;i<nlstate;i++){ */
                   13451:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13452:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13453:       /* } */
1.126     brouard  13454:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13455:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13456:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13457:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13458:     fclose (ficparo);
                   13459:     fclose (ficlog);
                   13460:     goto end;
                   13461:     exit(0);
1.220     brouard  13462:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13463:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13464:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13465:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13466:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13467:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13468:     hess=matrix(1,npar,1,npar);
1.220     brouard  13469:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13470:     /* Read guessed parameters */
1.126     brouard  13471:     /* Reads comments: lines beginning with '#' */
                   13472:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13473:       ungetc(c,ficpar);
                   13474:       fgets(line, MAXLINE, ficpar);
                   13475:       numlinepar++;
1.141     brouard  13476:       fputs(line,stdout);
1.126     brouard  13477:       fputs(line,ficparo);
                   13478:       fputs(line,ficlog);
                   13479:     }
                   13480:     ungetc(c,ficpar);
                   13481:     
                   13482:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13483:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13484:     for(i=1; i <=nlstate; i++){
1.234     brouard  13485:       j=0;
1.126     brouard  13486:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13487:        if(jj==i) continue;
                   13488:        j++;
1.292     brouard  13489:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13490:          ungetc(c,ficpar);
                   13491:          fgets(line, MAXLINE, ficpar);
                   13492:          numlinepar++;
                   13493:          fputs(line,stdout);
                   13494:          fputs(line,ficparo);
                   13495:          fputs(line,ficlog);
                   13496:        }
                   13497:        ungetc(c,ficpar);
1.234     brouard  13498:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13499:        if ((i1 != i) || (j1 != jj)){
                   13500:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13501: It might be a problem of design; if ncovcol and the model are correct\n \
                   13502: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13503:          exit(1);
                   13504:        }
                   13505:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13506:        if(mle==1)
                   13507:          printf("%1d%1d",i,jj);
                   13508:        fprintf(ficlog,"%1d%1d",i,jj);
                   13509:        for(k=1; k<=ncovmodel;k++){
                   13510:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13511:          if(mle==1){
                   13512:            printf(" %lf",param[i][j][k]);
                   13513:            fprintf(ficlog," %lf",param[i][j][k]);
                   13514:          }
                   13515:          else
                   13516:            fprintf(ficlog," %lf",param[i][j][k]);
                   13517:          fprintf(ficparo," %lf",param[i][j][k]);
                   13518:        }
                   13519:        fscanf(ficpar,"\n");
                   13520:        numlinepar++;
                   13521:        if(mle==1)
                   13522:          printf("\n");
                   13523:        fprintf(ficlog,"\n");
                   13524:        fprintf(ficparo,"\n");
1.126     brouard  13525:       }
                   13526:     }  
                   13527:     fflush(ficlog);
1.234     brouard  13528:     
1.251     brouard  13529:     /* Reads parameters values */
1.126     brouard  13530:     p=param[1][1];
1.251     brouard  13531:     pstart=paramstart[1][1];
1.126     brouard  13532:     
                   13533:     /* Reads comments: lines beginning with '#' */
                   13534:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13535:       ungetc(c,ficpar);
                   13536:       fgets(line, MAXLINE, ficpar);
                   13537:       numlinepar++;
1.141     brouard  13538:       fputs(line,stdout);
1.126     brouard  13539:       fputs(line,ficparo);
                   13540:       fputs(line,ficlog);
                   13541:     }
                   13542:     ungetc(c,ficpar);
                   13543: 
                   13544:     for(i=1; i <=nlstate; i++){
                   13545:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13546:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13547:        if ( (i1-i) * (j1-j) != 0){
                   13548:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13549:          exit(1);
                   13550:        }
                   13551:        printf("%1d%1d",i,j);
                   13552:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13553:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13554:        for(k=1; k<=ncovmodel;k++){
                   13555:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13556:          printf(" %le",delti3[i][j][k]);
                   13557:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13558:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13559:        }
                   13560:        fscanf(ficpar,"\n");
                   13561:        numlinepar++;
                   13562:        printf("\n");
                   13563:        fprintf(ficparo,"\n");
                   13564:        fprintf(ficlog,"\n");
1.126     brouard  13565:       }
                   13566:     }
                   13567:     fflush(ficlog);
1.234     brouard  13568:     
1.145     brouard  13569:     /* Reads covariance matrix */
1.126     brouard  13570:     delti=delti3[1][1];
1.220     brouard  13571:                
                   13572:                
1.126     brouard  13573:     /* 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  13574:                
1.126     brouard  13575:     /* Reads comments: lines beginning with '#' */
                   13576:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13577:       ungetc(c,ficpar);
                   13578:       fgets(line, MAXLINE, ficpar);
                   13579:       numlinepar++;
1.141     brouard  13580:       fputs(line,stdout);
1.126     brouard  13581:       fputs(line,ficparo);
                   13582:       fputs(line,ficlog);
                   13583:     }
                   13584:     ungetc(c,ficpar);
1.220     brouard  13585:                
1.126     brouard  13586:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13587:     hess=matrix(1,npar,1,npar);
1.131     brouard  13588:     for(i=1; i <=npar; i++)
                   13589:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13590:                
1.194     brouard  13591:     /* Scans npar lines */
1.126     brouard  13592:     for(i=1; i <=npar; i++){
1.226     brouard  13593:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13594:       if(count != 3){
1.226     brouard  13595:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13596: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13597: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13598:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13599: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13600: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13601:        exit(1);
1.220     brouard  13602:       }else{
1.226     brouard  13603:        if(mle==1)
                   13604:          printf("%1d%1d%d",i1,j1,jk);
                   13605:       }
                   13606:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13607:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13608:       for(j=1; j <=i; j++){
1.226     brouard  13609:        fscanf(ficpar," %le",&matcov[i][j]);
                   13610:        if(mle==1){
                   13611:          printf(" %.5le",matcov[i][j]);
                   13612:        }
                   13613:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13614:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13615:       }
                   13616:       fscanf(ficpar,"\n");
                   13617:       numlinepar++;
                   13618:       if(mle==1)
1.220     brouard  13619:                                printf("\n");
1.126     brouard  13620:       fprintf(ficlog,"\n");
                   13621:       fprintf(ficparo,"\n");
                   13622:     }
1.194     brouard  13623:     /* End of read covariance matrix npar lines */
1.126     brouard  13624:     for(i=1; i <=npar; i++)
                   13625:       for(j=i+1;j<=npar;j++)
1.226     brouard  13626:        matcov[i][j]=matcov[j][i];
1.126     brouard  13627:     
                   13628:     if(mle==1)
                   13629:       printf("\n");
                   13630:     fprintf(ficlog,"\n");
                   13631:     
                   13632:     fflush(ficlog);
                   13633:     
                   13634:   }    /* End of mle != -3 */
1.218     brouard  13635:   
1.186     brouard  13636:   /*  Main data
                   13637:    */
1.290     brouard  13638:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13639:   /* num=lvector(1,n); */
                   13640:   /* moisnais=vector(1,n); */
                   13641:   /* annais=vector(1,n); */
                   13642:   /* moisdc=vector(1,n); */
                   13643:   /* andc=vector(1,n); */
                   13644:   /* weight=vector(1,n); */
                   13645:   /* agedc=vector(1,n); */
                   13646:   /* cod=ivector(1,n); */
                   13647:   /* for(i=1;i<=n;i++){ */
                   13648:   num=lvector(firstobs,lastobs);
                   13649:   moisnais=vector(firstobs,lastobs);
                   13650:   annais=vector(firstobs,lastobs);
                   13651:   moisdc=vector(firstobs,lastobs);
                   13652:   andc=vector(firstobs,lastobs);
                   13653:   weight=vector(firstobs,lastobs);
                   13654:   agedc=vector(firstobs,lastobs);
                   13655:   cod=ivector(firstobs,lastobs);
                   13656:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13657:     num[i]=0;
                   13658:     moisnais[i]=0;
                   13659:     annais[i]=0;
                   13660:     moisdc[i]=0;
                   13661:     andc[i]=0;
                   13662:     agedc[i]=0;
                   13663:     cod[i]=0;
                   13664:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13665:   }
1.290     brouard  13666:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13667:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13668:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13669:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13670:   tab=ivector(1,NCOVMAX);
1.144     brouard  13671:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13672:   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  13673: 
1.136     brouard  13674:   /* Reads data from file datafile */
                   13675:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13676:     goto end;
                   13677: 
                   13678:   /* Calculation of the number of parameters from char model */
1.234     brouard  13679:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13680:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13681:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13682:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13683:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13684:   */
                   13685:   
                   13686:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13687:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13688:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13689:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13690:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13691:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13692:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13693:   TvarF=ivector(1,NCOVMAX); /*  */
                   13694:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13695:   TvarV=ivector(1,NCOVMAX); /*  */
                   13696:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13697:   TvarA=ivector(1,NCOVMAX); /*  */
                   13698:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13699:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13700:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13701:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13702:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13703:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13704:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13705:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13706:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13707:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13708:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13709:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13710:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13711:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13712:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13713: 
1.230     brouard  13714:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13715:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13716:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13717:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13718:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13719:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13720:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13721: 
1.137     brouard  13722:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13723:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13724:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13725:   */
                   13726:   /* For model-covariate k tells which data-covariate to use but
                   13727:     because this model-covariate is a construction we invent a new column
                   13728:     ncovcol + k1
                   13729:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13730:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13731:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13732:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13733:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13734:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13735:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13736:   */
1.145     brouard  13737:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13738:   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  13739:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13740:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  13741:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  13742:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13743:                         4 covariates (3 plus signs)
                   13744:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13745:                           */  
                   13746:   for(i=1;i<NCOVMAX;i++)
                   13747:     Tage[i]=0;
1.230     brouard  13748:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13749:                                * individual dummy, fixed or varying:
                   13750:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13751:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13752:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13753:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13754:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13755:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13756:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13757:                                * individual quantitative, fixed or varying:
                   13758:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13759:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13760:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13761: 
                   13762: /* Probably useless zeroes */
                   13763:   for(i=1;i<NCOVMAX;i++){
                   13764:     DummyV[i]=0;
                   13765:     FixedV[i]=0;
                   13766:   }
                   13767: 
                   13768:   for(i=1; i <=ncovcol;i++){
                   13769:     DummyV[i]=0;
                   13770:     FixedV[i]=0;
                   13771:   }
                   13772:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13773:     DummyV[i]=1;
                   13774:     FixedV[i]=0;
                   13775:   }
                   13776:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13777:     DummyV[i]=0;
                   13778:     FixedV[i]=1;
                   13779:   }
                   13780:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13781:     DummyV[i]=1;
                   13782:     FixedV[i]=1;
                   13783:   }
                   13784:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13785:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13786:     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]);
                   13787:   }
                   13788: 
                   13789: 
                   13790: 
1.186     brouard  13791: /* Main decodemodel */
                   13792: 
1.187     brouard  13793: 
1.223     brouard  13794:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13795:     goto end;
                   13796: 
1.137     brouard  13797:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13798:     nbwarn++;
                   13799:     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); 
                   13800:     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); 
                   13801:   }
1.136     brouard  13802:     /*  if(mle==1){*/
1.137     brouard  13803:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13804:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13805:   }
                   13806: 
                   13807:     /*-calculation of age at interview from date of interview and age at death -*/
                   13808:   agev=matrix(1,maxwav,1,imx);
                   13809: 
                   13810:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13811:     goto end;
                   13812: 
1.126     brouard  13813: 
1.136     brouard  13814:   agegomp=(int)agemin;
1.290     brouard  13815:   free_vector(moisnais,firstobs,lastobs);
                   13816:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13817:   /* free_matrix(mint,1,maxwav,1,n);
                   13818:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13819:   /* free_vector(moisdc,1,n); */
                   13820:   /* free_vector(andc,1,n); */
1.145     brouard  13821:   /* */
                   13822:   
1.126     brouard  13823:   wav=ivector(1,imx);
1.214     brouard  13824:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13825:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13826:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13827:   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.*/
                   13828:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13829:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13830:    
                   13831:   /* Concatenates waves */
1.214     brouard  13832:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13833:      Death is a valid wave (if date is known).
                   13834:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13835:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13836:      and mw[mi+1][i]. dh depends on stepm.
                   13837:   */
                   13838: 
1.126     brouard  13839:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13840:   /* Concatenates waves */
1.145     brouard  13841:  
1.290     brouard  13842:   free_vector(moisdc,firstobs,lastobs);
                   13843:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13844: 
1.126     brouard  13845:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13846:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13847:   ncodemax[1]=1;
1.145     brouard  13848:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13849:   cptcoveff=0;
1.220     brouard  13850:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13851:     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  13852:   }
                   13853:   
                   13854:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13855:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13856:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13857:     invalidvarcomb[i]=0;
                   13858:   
1.211     brouard  13859:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13860:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13861:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13862:   
1.200     brouard  13863:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13864:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13865:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13866:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13867:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13868:    * (currently 0 or 1) in the data.
                   13869:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13870:    * corresponding modality (h,j).
                   13871:    */
                   13872: 
1.145     brouard  13873:   h=0;
                   13874:   /*if (cptcovn > 0) */
1.126     brouard  13875:   m=pow(2,cptcoveff);
                   13876:  
1.144     brouard  13877:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13878:           * For k=4 covariates, h goes from 1 to m=2**k
                   13879:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13880:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13881:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13882:           *______________________________   *______________________
                   13883:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13884:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13885:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13886:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13887:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13888:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13889:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13890:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13891:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13892:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13893:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13894:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13895:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13896:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13897:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13898:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13899:           */                                     
1.212     brouard  13900:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13901:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13902:      * and the value of each covariate?
                   13903:      * V1=1, V2=1, V3=2, V4=1 ?
                   13904:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13905:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13906:      * In order to get the real value in the data, we use nbcode
                   13907:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13908:      * We are keeping this crazy system in order to be able (in the future?) 
                   13909:      * to have more than 2 values (0 or 1) for a covariate.
                   13910:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13911:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13912:      *              bbbbbbbb
                   13913:      *              76543210     
                   13914:      *   h-1        00000101 (6-1=5)
1.219     brouard  13915:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13916:      *           &
                   13917:      *     1        00000001 (1)
1.219     brouard  13918:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13919:      *          +1= 00000001 =1 
1.211     brouard  13920:      *
                   13921:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13922:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13923:      *    >>k'            11
                   13924:      *          &   00000001
                   13925:      *            = 00000001
                   13926:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13927:      * Reverse h=6 and m=16?
                   13928:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13929:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13930:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13931:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13932:      * V3=decodtabm(14,3,2**4)=2
                   13933:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13934:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13935:      *          &1 000000001
                   13936:      *           = 000000001
                   13937:      *         +1= 000000010 =2
                   13938:      *                  2211
                   13939:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13940:      *                  V3=2
1.220     brouard  13941:                 * codtabm and decodtabm are identical
1.211     brouard  13942:      */
                   13943: 
1.145     brouard  13944: 
                   13945:  free_ivector(Ndum,-1,NCOVMAX);
                   13946: 
                   13947: 
1.126     brouard  13948:     
1.186     brouard  13949:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13950:   strcpy(optionfilegnuplot,optionfilefiname);
                   13951:   if(mle==-3)
1.201     brouard  13952:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13953:   strcat(optionfilegnuplot,".gp");
                   13954: 
                   13955:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13956:     printf("Problem with file %s",optionfilegnuplot);
                   13957:   }
                   13958:   else{
1.204     brouard  13959:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13960:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13961:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13962:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13963:   }
                   13964:   /*  fclose(ficgp);*/
1.186     brouard  13965: 
                   13966: 
                   13967:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13968: 
                   13969:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13970:   if(mle==-3)
1.201     brouard  13971:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13972:   strcat(optionfilehtm,".htm");
                   13973:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13974:     printf("Problem with %s \n",optionfilehtm);
                   13975:     exit(0);
1.126     brouard  13976:   }
                   13977: 
                   13978:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13979:   strcat(optionfilehtmcov,"-cov.htm");
                   13980:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13981:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13982:   }
                   13983:   else{
                   13984:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13985: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13986: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13987:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13988:   }
                   13989: 
1.335     brouard  13990:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13991: <title>IMaCh %s</title></head>\n\
                   13992:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13993: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13994: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13995: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13996: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13997:   
                   13998:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13999: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  14000: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  14001: 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  14002: \n\
                   14003: <hr  size=\"2\" color=\"#EC5E5E\">\
                   14004:  <ul><li><h4>Parameter files</h4>\n\
                   14005:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   14006:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   14007:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   14008:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   14009:  - Date and time at start: %s</ul>\n",\
1.335     brouard  14010:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  14011:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   14012:          fileres,fileres,\
                   14013:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   14014:   fflush(fichtm);
                   14015: 
                   14016:   strcpy(pathr,path);
                   14017:   strcat(pathr,optionfilefiname);
1.184     brouard  14018: #ifdef WIN32
                   14019:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14020: #else
1.126     brouard  14021:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  14022: #endif
                   14023:          
1.126     brouard  14024:   
1.220     brouard  14025:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14026:                 and for any valid combination of covariates
1.126     brouard  14027:      and prints on file fileres'p'. */
1.251     brouard  14028:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  14029:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  14030: 
                   14031:   fprintf(fichtm,"\n");
1.286     brouard  14032:   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  14033:          ftol, stepm);
                   14034:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14035:   ncurrv=1;
                   14036:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14037:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14038:   ncurrv=i;
                   14039:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14040:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  14041:   ncurrv=i;
                   14042:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14043:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  14044:   ncurrv=i;
                   14045:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14046:   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", \
                   14047:           nlstate, ndeath, maxwav, mle, weightopt);
                   14048: 
                   14049:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14050: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14051: 
                   14052:   
1.317     brouard  14053:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  14054: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14055: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  14056:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  14057:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  14058:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14059:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14060:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14061:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  14062: 
1.126     brouard  14063:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14064:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14065:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14066: 
                   14067:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  14068:   /* For mortality only */
1.126     brouard  14069:   if (mle==-3){
1.136     brouard  14070:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  14071:     for(i=1;i<=NDIM;i++)
                   14072:       for(j=1;j<=NDIM;j++)
                   14073:        ximort[i][j]=0.;
1.186     brouard  14074:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  14075:     cens=ivector(firstobs,lastobs);
                   14076:     ageexmed=vector(firstobs,lastobs);
                   14077:     agecens=vector(firstobs,lastobs);
                   14078:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  14079:                
1.126     brouard  14080:     for (i=1; i<=imx; i++){
                   14081:       dcwave[i]=-1;
                   14082:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  14083:        if (s[m][i]>nlstate) {
                   14084:          dcwave[i]=m;
                   14085:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14086:          break;
                   14087:        }
1.126     brouard  14088:     }
1.226     brouard  14089:     
1.126     brouard  14090:     for (i=1; i<=imx; i++) {
                   14091:       if (wav[i]>0){
1.226     brouard  14092:        ageexmed[i]=agev[mw[1][i]][i];
                   14093:        j=wav[i];
                   14094:        agecens[i]=1.; 
                   14095:        
                   14096:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14097:          agecens[i]=agev[mw[j][i]][i];
                   14098:          cens[i]= 1;
                   14099:        }else if (ageexmed[i]< 1) 
                   14100:          cens[i]= -1;
                   14101:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14102:          cens[i]=0 ;
1.126     brouard  14103:       }
                   14104:       else cens[i]=-1;
                   14105:     }
                   14106:     
                   14107:     for (i=1;i<=NDIM;i++) {
                   14108:       for (j=1;j<=NDIM;j++)
1.226     brouard  14109:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14110:     }
                   14111:     
1.302     brouard  14112:     p[1]=0.0268; p[NDIM]=0.083;
                   14113:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14114:     
                   14115:     
1.136     brouard  14116: #ifdef GSL
                   14117:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14118: #else
1.126     brouard  14119:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14120: #endif
1.201     brouard  14121:     strcpy(filerespow,"POW-MORT_"); 
                   14122:     strcat(filerespow,fileresu);
1.126     brouard  14123:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14124:       printf("Problem with resultfile: %s\n", filerespow);
                   14125:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14126:     }
1.136     brouard  14127: #ifdef GSL
                   14128:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14129: #else
1.126     brouard  14130:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14131: #endif
1.126     brouard  14132:     /*  for (i=1;i<=nlstate;i++)
                   14133:        for(j=1;j<=nlstate+ndeath;j++)
                   14134:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14135:     */
                   14136:     fprintf(ficrespow,"\n");
1.136     brouard  14137: #ifdef GSL
                   14138:     /* gsl starts here */ 
                   14139:     T = gsl_multimin_fminimizer_nmsimplex;
                   14140:     gsl_multimin_fminimizer *sfm = NULL;
                   14141:     gsl_vector *ss, *x;
                   14142:     gsl_multimin_function minex_func;
                   14143: 
                   14144:     /* Initial vertex size vector */
                   14145:     ss = gsl_vector_alloc (NDIM);
                   14146:     
                   14147:     if (ss == NULL){
                   14148:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14149:     }
                   14150:     /* Set all step sizes to 1 */
                   14151:     gsl_vector_set_all (ss, 0.001);
                   14152: 
                   14153:     /* Starting point */
1.126     brouard  14154:     
1.136     brouard  14155:     x = gsl_vector_alloc (NDIM);
                   14156:     
                   14157:     if (x == NULL){
                   14158:       gsl_vector_free(ss);
                   14159:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14160:     }
                   14161:   
                   14162:     /* Initialize method and iterate */
                   14163:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14164:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14165:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14166:     gsl_vector_set(x, 0, p[1]);
                   14167:     gsl_vector_set(x, 1, p[2]);
                   14168: 
                   14169:     minex_func.f = &gompertz_f;
                   14170:     minex_func.n = NDIM;
                   14171:     minex_func.params = (void *)&p; /* ??? */
                   14172:     
                   14173:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14174:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14175:     
                   14176:     printf("Iterations beginning .....\n\n");
                   14177:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14178: 
                   14179:     iteri=0;
                   14180:     while (rval == GSL_CONTINUE){
                   14181:       iteri++;
                   14182:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14183:       
                   14184:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14185:       fflush(0);
                   14186:       
                   14187:       if (status) 
                   14188:         break;
                   14189:       
                   14190:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14191:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14192:       
                   14193:       if (rval == GSL_SUCCESS)
                   14194:         printf ("converged to a local maximum at\n");
                   14195:       
                   14196:       printf("%5d ", iteri);
                   14197:       for (it = 0; it < NDIM; it++){
                   14198:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14199:       }
                   14200:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14201:     }
                   14202:     
                   14203:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14204:     
                   14205:     gsl_vector_free(x); /* initial values */
                   14206:     gsl_vector_free(ss); /* inital step size */
                   14207:     for (it=0; it<NDIM; it++){
                   14208:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14209:       fprintf(ficrespow," %.12lf", p[it]);
                   14210:     }
                   14211:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14212: #endif
                   14213: #ifdef POWELL
                   14214:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14215: #endif  
1.126     brouard  14216:     fclose(ficrespow);
                   14217:     
1.203     brouard  14218:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14219: 
                   14220:     for(i=1; i <=NDIM; i++)
                   14221:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14222:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14223:     
                   14224:     printf("\nCovariance matrix\n ");
1.203     brouard  14225:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14226:     for(i=1; i <=NDIM; i++) {
                   14227:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14228:                                printf("%f ",matcov[i][j]);
                   14229:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14230:       }
1.203     brouard  14231:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14232:     }
                   14233:     
                   14234:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14235:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14236:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14237:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14238:     }
1.302     brouard  14239:     lsurv=vector(agegomp,AGESUP);
                   14240:     lpop=vector(agegomp,AGESUP);
                   14241:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14242:     lsurv[agegomp]=100000;
                   14243:     
                   14244:     for (k=agegomp;k<=AGESUP;k++) {
                   14245:       agemortsup=k;
                   14246:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14247:     }
                   14248:     
                   14249:     for (k=agegomp;k<agemortsup;k++)
                   14250:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14251:     
                   14252:     for (k=agegomp;k<agemortsup;k++){
                   14253:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14254:       sumlpop=sumlpop+lpop[k];
                   14255:     }
                   14256:     
                   14257:     tpop[agegomp]=sumlpop;
                   14258:     for (k=agegomp;k<(agemortsup-3);k++){
                   14259:       /*  tpop[k+1]=2;*/
                   14260:       tpop[k+1]=tpop[k]-lpop[k];
                   14261:     }
                   14262:     
                   14263:     
                   14264:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14265:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14266:       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]);
                   14267:     
                   14268:     
                   14269:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14270:                ageminpar=50;
                   14271:                agemaxpar=100;
1.194     brouard  14272:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14273:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14274: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14275: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14276:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14277: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14278: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14279:     }else{
                   14280:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14281:                        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  14282:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14283:                }
1.201     brouard  14284:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14285:                     stepm, weightopt,\
                   14286:                     model,imx,p,matcov,agemortsup);
                   14287:     
1.302     brouard  14288:     free_vector(lsurv,agegomp,AGESUP);
                   14289:     free_vector(lpop,agegomp,AGESUP);
                   14290:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14291:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14292:     free_ivector(dcwave,firstobs,lastobs);
                   14293:     free_vector(agecens,firstobs,lastobs);
                   14294:     free_vector(ageexmed,firstobs,lastobs);
                   14295:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14296: #ifdef GSL
1.136     brouard  14297: #endif
1.186     brouard  14298:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14299:   /* Standard  */
                   14300:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14301:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14302:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14303:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14304:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14305:     for (k=1; k<=npar;k++)
                   14306:       printf(" %d %8.5f",k,p[k]);
                   14307:     printf("\n");
1.205     brouard  14308:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14309:       /* mlikeli uses func not funcone */
1.247     brouard  14310:       /* for(i=1;i<nlstate;i++){ */
                   14311:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14312:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14313:       /* } */
1.205     brouard  14314:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14315:     }
                   14316:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14317:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14318:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14319:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14320:     }
                   14321:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14322:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14323:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14324:           /* exit(0); */
1.126     brouard  14325:     for (k=1; k<=npar;k++)
                   14326:       printf(" %d %8.5f",k,p[k]);
                   14327:     printf("\n");
                   14328:     
                   14329:     /*--------- results files --------------*/
1.283     brouard  14330:     /* 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  14331:     
                   14332:     
                   14333:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14334:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14335:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14336: 
                   14337:     printf("#model=  1      +     age ");
                   14338:     fprintf(ficres,"#model=  1      +     age ");
                   14339:     fprintf(ficlog,"#model=  1      +     age ");
                   14340:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14341: </ul>", model);
                   14342: 
                   14343:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14344:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14345:     if(nagesqr==1){
                   14346:       printf("  + age*age  ");
                   14347:       fprintf(ficres,"  + age*age  ");
                   14348:       fprintf(ficlog,"  + age*age  ");
                   14349:       fprintf(fichtm, "<th>+ age*age</th>");
                   14350:     }
                   14351:     for(j=1;j <=ncovmodel-2;j++){
                   14352:       if(Typevar[j]==0) {
                   14353:        printf("  +      V%d  ",Tvar[j]);
                   14354:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14355:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14356:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14357:       }else if(Typevar[j]==1) {
                   14358:        printf("  +    V%d*age ",Tvar[j]);
                   14359:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14360:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14361:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14362:       }else if(Typevar[j]==2) {
                   14363:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14364:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14365:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14366:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14367:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14368:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14369:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14370:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14371:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14372:       }
                   14373:     }
                   14374:     printf("\n");
                   14375:     fprintf(ficres,"\n");
                   14376:     fprintf(ficlog,"\n");
                   14377:     fprintf(fichtm, "</tr>");
                   14378:     fprintf(fichtm, "\n");
                   14379:     
                   14380:     
1.126     brouard  14381:     for(i=1,jk=1; i <=nlstate; i++){
                   14382:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14383:        if (k != i) {
1.319     brouard  14384:          fprintf(fichtm, "<tr>");
1.225     brouard  14385:          printf("%d%d ",i,k);
                   14386:          fprintf(ficlog,"%d%d ",i,k);
                   14387:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14388:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14389:          for(j=1; j <=ncovmodel; j++){
                   14390:            printf("%12.7f ",p[jk]);
                   14391:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14392:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14393:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14394:            jk++; 
                   14395:          }
                   14396:          printf("\n");
                   14397:          fprintf(ficlog,"\n");
                   14398:          fprintf(ficres,"\n");
1.319     brouard  14399:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14400:        }
1.126     brouard  14401:       }
                   14402:     }
1.319     brouard  14403:     /* fprintf(fichtm,"</tr>\n"); */
                   14404:     fprintf(fichtm,"</table>\n");
                   14405:     fprintf(fichtm, "\n");
                   14406: 
1.203     brouard  14407:     if(mle != 0){
                   14408:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14409:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14410:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14411:       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");
                   14412:       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  14413:       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  14414:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14415:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14416:       if(nagesqr==1){
                   14417:        printf("  + age*age  ");
                   14418:        fprintf(ficres,"  + age*age  ");
                   14419:        fprintf(ficlog,"  + age*age  ");
                   14420:        fprintf(fichtm, "<th>+ age*age</th>");
                   14421:       }
                   14422:       for(j=1;j <=ncovmodel-2;j++){
                   14423:        if(Typevar[j]==0) {
                   14424:          printf("  +      V%d  ",Tvar[j]);
                   14425:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14426:        }else if(Typevar[j]==1) {
                   14427:          printf("  +    V%d*age ",Tvar[j]);
                   14428:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14429:        }else if(Typevar[j]==2) {
                   14430:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14431:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14432:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14433:        }
                   14434:       }
                   14435:       fprintf(fichtm, "</tr>\n");
                   14436:  
1.203     brouard  14437:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14438:        for(k=1; k <=(nlstate+ndeath); k++){
                   14439:          if (k != i) {
1.319     brouard  14440:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14441:            printf("%d%d ",i,k);
                   14442:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14443:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14444:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14445:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14446:              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]));
                   14447:              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  14448:              if(fabs(wald) > 1.96){
1.321     brouard  14449:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14450:              }else{
                   14451:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14452:              }
1.324     brouard  14453:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14454:              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  14455:              jk++; 
                   14456:            }
                   14457:            printf("\n");
                   14458:            fprintf(ficlog,"\n");
1.319     brouard  14459:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14460:          }
                   14461:        }
1.193     brouard  14462:       }
1.203     brouard  14463:     } /* end of hesscov and Wald tests */
1.319     brouard  14464:     fprintf(fichtm,"</table>\n");
1.225     brouard  14465:     
1.203     brouard  14466:     /*  */
1.126     brouard  14467:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14468:     printf("# Scales (for hessian or gradient estimation)\n");
                   14469:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14470:     for(i=1,jk=1; i <=nlstate; i++){
                   14471:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14472:        if (j!=i) {
                   14473:          fprintf(ficres,"%1d%1d",i,j);
                   14474:          printf("%1d%1d",i,j);
                   14475:          fprintf(ficlog,"%1d%1d",i,j);
                   14476:          for(k=1; k<=ncovmodel;k++){
                   14477:            printf(" %.5e",delti[jk]);
                   14478:            fprintf(ficlog," %.5e",delti[jk]);
                   14479:            fprintf(ficres," %.5e",delti[jk]);
                   14480:            jk++;
                   14481:          }
                   14482:          printf("\n");
                   14483:          fprintf(ficlog,"\n");
                   14484:          fprintf(ficres,"\n");
                   14485:        }
1.126     brouard  14486:       }
                   14487:     }
                   14488:     
                   14489:     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  14490:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14491:       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");
                   14492:     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");
                   14493:     /* # 121 Var(a12)\n\ */
                   14494:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14495:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14496:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14497:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14498:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14499:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14500:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14501:     
                   14502:     
                   14503:     /* Just to have a covariance matrix which will be more understandable
                   14504:        even is we still don't want to manage dictionary of variables
                   14505:     */
                   14506:     for(itimes=1;itimes<=2;itimes++){
                   14507:       jj=0;
                   14508:       for(i=1; i <=nlstate; i++){
1.225     brouard  14509:        for(j=1; j <=nlstate+ndeath; j++){
                   14510:          if(j==i) continue;
                   14511:          for(k=1; k<=ncovmodel;k++){
                   14512:            jj++;
                   14513:            ca[0]= k+'a'-1;ca[1]='\0';
                   14514:            if(itimes==1){
                   14515:              if(mle>=1)
                   14516:                printf("#%1d%1d%d",i,j,k);
                   14517:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14518:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14519:            }else{
                   14520:              if(mle>=1)
                   14521:                printf("%1d%1d%d",i,j,k);
                   14522:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14523:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14524:            }
                   14525:            ll=0;
                   14526:            for(li=1;li <=nlstate; li++){
                   14527:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14528:                if(lj==li) continue;
                   14529:                for(lk=1;lk<=ncovmodel;lk++){
                   14530:                  ll++;
                   14531:                  if(ll<=jj){
                   14532:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14533:                    if(ll<jj){
                   14534:                      if(itimes==1){
                   14535:                        if(mle>=1)
                   14536:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14537:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14538:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14539:                      }else{
                   14540:                        if(mle>=1)
                   14541:                          printf(" %.5e",matcov[jj][ll]); 
                   14542:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14543:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14544:                      }
                   14545:                    }else{
                   14546:                      if(itimes==1){
                   14547:                        if(mle>=1)
                   14548:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14549:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14550:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14551:                      }else{
                   14552:                        if(mle>=1)
                   14553:                          printf(" %.7e",matcov[jj][ll]); 
                   14554:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14555:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14556:                      }
                   14557:                    }
                   14558:                  }
                   14559:                } /* end lk */
                   14560:              } /* end lj */
                   14561:            } /* end li */
                   14562:            if(mle>=1)
                   14563:              printf("\n");
                   14564:            fprintf(ficlog,"\n");
                   14565:            fprintf(ficres,"\n");
                   14566:            numlinepar++;
                   14567:          } /* end k*/
                   14568:        } /*end j */
1.126     brouard  14569:       } /* end i */
                   14570:     } /* end itimes */
                   14571:     
                   14572:     fflush(ficlog);
                   14573:     fflush(ficres);
1.225     brouard  14574:     while(fgets(line, MAXLINE, ficpar)) {
                   14575:       /* If line starts with a # it is a comment */
                   14576:       if (line[0] == '#') {
                   14577:        numlinepar++;
                   14578:        fputs(line,stdout);
                   14579:        fputs(line,ficparo);
                   14580:        fputs(line,ficlog);
1.299     brouard  14581:        fputs(line,ficres);
1.225     brouard  14582:        continue;
                   14583:       }else
                   14584:        break;
                   14585:     }
                   14586:     
1.209     brouard  14587:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14588:     /*   ungetc(c,ficpar); */
                   14589:     /*   fgets(line, MAXLINE, ficpar); */
                   14590:     /*   fputs(line,stdout); */
                   14591:     /*   fputs(line,ficparo); */
                   14592:     /* } */
                   14593:     /* ungetc(c,ficpar); */
1.126     brouard  14594:     
                   14595:     estepm=0;
1.209     brouard  14596:     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  14597:       
                   14598:       if (num_filled != 6) {
                   14599:        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);
                   14600:        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);
                   14601:        goto end;
                   14602:       }
                   14603:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14604:     }
                   14605:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14606:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14607:     
1.209     brouard  14608:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14609:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14610:     if (fage <= 2) {
                   14611:       bage = ageminpar;
                   14612:       fage = agemaxpar;
                   14613:     }
                   14614:     
                   14615:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14616:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14617:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14618:                
1.186     brouard  14619:     /* Other stuffs, more or less useful */    
1.254     brouard  14620:     while(fgets(line, MAXLINE, ficpar)) {
                   14621:       /* If line starts with a # it is a comment */
                   14622:       if (line[0] == '#') {
                   14623:        numlinepar++;
                   14624:        fputs(line,stdout);
                   14625:        fputs(line,ficparo);
                   14626:        fputs(line,ficlog);
1.299     brouard  14627:        fputs(line,ficres);
1.254     brouard  14628:        continue;
                   14629:       }else
                   14630:        break;
                   14631:     }
                   14632: 
                   14633:     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){
                   14634:       
                   14635:       if (num_filled != 7) {
                   14636:        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);
                   14637:        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);
                   14638:        goto end;
                   14639:       }
                   14640:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14641:       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);
                   14642:       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);
                   14643:       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  14644:     }
1.254     brouard  14645: 
                   14646:     while(fgets(line, MAXLINE, ficpar)) {
                   14647:       /* If line starts with a # it is a comment */
                   14648:       if (line[0] == '#') {
                   14649:        numlinepar++;
                   14650:        fputs(line,stdout);
                   14651:        fputs(line,ficparo);
                   14652:        fputs(line,ficlog);
1.299     brouard  14653:        fputs(line,ficres);
1.254     brouard  14654:        continue;
                   14655:       }else
                   14656:        break;
1.126     brouard  14657:     }
                   14658:     
                   14659:     
                   14660:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14661:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14662:     
1.254     brouard  14663:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14664:       if (num_filled != 1) {
                   14665:        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);
                   14666:        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);
                   14667:        goto end;
                   14668:       }
                   14669:       printf("pop_based=%d\n",popbased);
                   14670:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14671:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14672:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14673:     }
                   14674:      
1.258     brouard  14675:     /* Results */
1.332     brouard  14676:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14677:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14678:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14679:     endishere=0;
1.258     brouard  14680:     nresult=0;
1.308     brouard  14681:     parameterline=0;
1.258     brouard  14682:     do{
                   14683:       if(!fgets(line, MAXLINE, ficpar)){
                   14684:        endishere=1;
1.308     brouard  14685:        parameterline=15;
1.258     brouard  14686:       }else if (line[0] == '#') {
                   14687:        /* If line starts with a # it is a comment */
1.254     brouard  14688:        numlinepar++;
                   14689:        fputs(line,stdout);
                   14690:        fputs(line,ficparo);
                   14691:        fputs(line,ficlog);
1.299     brouard  14692:        fputs(line,ficres);
1.254     brouard  14693:        continue;
1.258     brouard  14694:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14695:        parameterline=11;
1.296     brouard  14696:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14697:        parameterline=12;
1.307     brouard  14698:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14699:        parameterline=13;
1.307     brouard  14700:       }
1.258     brouard  14701:       else{
                   14702:        parameterline=14;
1.254     brouard  14703:       }
1.308     brouard  14704:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14705:       case 11:
1.296     brouard  14706:        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)){
                   14707:                  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  14708:          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);
                   14709:          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);
                   14710:          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);
                   14711:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14712:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14713:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14714:           prvforecast = 1;
                   14715:        } 
                   14716:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14717:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14718:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14719:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14720:           prvforecast = 2;
                   14721:        }
                   14722:        else {
                   14723:          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);
                   14724:          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);
                   14725:          goto end;
1.258     brouard  14726:        }
1.254     brouard  14727:        break;
1.258     brouard  14728:       case 12:
1.296     brouard  14729:        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)){
                   14730:           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);
                   14731:          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);
                   14732:          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);
                   14733:          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);
                   14734:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14735:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14736:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14737:           prvbackcast = 1;
                   14738:        } 
                   14739:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14740:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14741:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14742:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14743:           prvbackcast = 2;
                   14744:        }
                   14745:        else {
                   14746:          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);
                   14747:          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);
                   14748:          goto end;
1.258     brouard  14749:        }
1.230     brouard  14750:        break;
1.258     brouard  14751:       case 13:
1.332     brouard  14752:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14753:        nresult++; /* Sum of resultlines */
1.342     brouard  14754:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14755:        /* removefirstspace(&resultlineori); */
                   14756:        
                   14757:        if(strstr(resultlineori,"v") !=0){
                   14758:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14759:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14760:          return 1;
                   14761:        }
                   14762:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14763:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14764:        if(nresult > MAXRESULTLINESPONE-1){
                   14765:          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);
                   14766:          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  14767:          goto end;
                   14768:        }
1.332     brouard  14769:        
1.310     brouard  14770:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14771:          fprintf(ficparo,"result: %s\n",resultline);
                   14772:          fprintf(ficres,"result: %s\n",resultline);
                   14773:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14774:        } else
                   14775:          goto end;
1.307     brouard  14776:        break;
                   14777:       case 14:
                   14778:        printf("Error: Unknown command '%s'\n",line);
                   14779:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14780:        if(line[0] == ' ' || line[0] == '\n'){
                   14781:          printf("It should not be an empty line '%s'\n",line);
                   14782:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14783:        }         
1.307     brouard  14784:        if(ncovmodel >=2 && nresult==0 ){
                   14785:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14786:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14787:        }
1.307     brouard  14788:        /* goto end; */
                   14789:        break;
1.308     brouard  14790:       case 15:
                   14791:        printf("End of resultlines.\n");
                   14792:        fprintf(ficlog,"End of resultlines.\n");
                   14793:        break;
                   14794:       default: /* parameterline =0 */
1.307     brouard  14795:        nresult=1;
                   14796:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14797:       } /* End switch parameterline */
                   14798:     }while(endishere==0); /* End do */
1.126     brouard  14799:     
1.230     brouard  14800:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14801:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14802:     
                   14803:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14804:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14805:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14806: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14807: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14808:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14809: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14810: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14811:     }else{
1.270     brouard  14812:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14813:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14814:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14815:       if(prvforecast==1){
                   14816:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14817:         jprojd=jproj1;
                   14818:         mprojd=mproj1;
                   14819:         anprojd=anproj1;
                   14820:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14821:         jprojf=jproj2;
                   14822:         mprojf=mproj2;
                   14823:         anprojf=anproj2;
                   14824:       } else if(prvforecast == 2){
                   14825:         dateprojd=dateintmean;
                   14826:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14827:         dateprojf=dateintmean+yrfproj;
                   14828:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14829:       }
                   14830:       if(prvbackcast==1){
                   14831:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14832:         jbackd=jback1;
                   14833:         mbackd=mback1;
                   14834:         anbackd=anback1;
                   14835:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14836:         jbackf=jback2;
                   14837:         mbackf=mback2;
                   14838:         anbackf=anback2;
                   14839:       } else if(prvbackcast == 2){
                   14840:         datebackd=dateintmean;
                   14841:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14842:         datebackf=dateintmean-yrbproj;
                   14843:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14844:       }
                   14845:       
1.350     brouard  14846:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14847:     }
                   14848:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14849:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14850:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14851:                
1.225     brouard  14852:     /*------------ free_vector  -------------*/
                   14853:     /*  chdir(path); */
1.220     brouard  14854:                
1.215     brouard  14855:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14856:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14857:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14858:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14859:     free_lvector(num,firstobs,lastobs);
                   14860:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14861:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14862:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14863:     fclose(ficparo);
                   14864:     fclose(ficres);
1.220     brouard  14865:                
                   14866:                
1.186     brouard  14867:     /* Other results (useful)*/
1.220     brouard  14868:                
                   14869:                
1.126     brouard  14870:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14871:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14872:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14873:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14874:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14875:     fclose(ficrespl);
                   14876: 
                   14877:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14878:     /*#include "hpijx.h"*/
1.332     brouard  14879:     /** 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?*/
                   14880:     /* calls hpxij with combination k */
1.180     brouard  14881:     hPijx(p, bage, fage);
1.145     brouard  14882:     fclose(ficrespij);
1.227     brouard  14883:     
1.220     brouard  14884:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14885:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14886:     k=1;
1.126     brouard  14887:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14888:     
1.269     brouard  14889:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14890:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14891:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14892:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14893:        for(k=1;k<=ncovcombmax;k++)
                   14894:          probs[i][j][k]=0.;
1.269     brouard  14895:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14896:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14897:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14898:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14899:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14900:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14901:          for(k=1;k<=ncovcombmax;k++)
                   14902:            mobaverages[i][j][k]=0.;
1.219     brouard  14903:       mobaverage=mobaverages;
                   14904:       if (mobilav!=0) {
1.235     brouard  14905:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14906:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14907:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14908:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14909:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14910:        }
1.269     brouard  14911:       } else if (mobilavproj !=0) {
1.235     brouard  14912:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14913:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14914:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14915:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14916:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14917:        }
1.269     brouard  14918:       }else{
                   14919:        printf("Internal error moving average\n");
                   14920:        fflush(stdout);
                   14921:        exit(1);
1.219     brouard  14922:       }
                   14923:     }/* end if moving average */
1.227     brouard  14924:     
1.126     brouard  14925:     /*---------- Forecasting ------------------*/
1.296     brouard  14926:     if(prevfcast==1){ 
                   14927:       /*   /\*    if(stepm ==1){*\/ */
                   14928:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14929:       /*This done previously after freqsummary.*/
                   14930:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14931:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14932:       
                   14933:       /* } else if (prvforecast==2){ */
                   14934:       /*   /\*    if(stepm ==1){*\/ */
                   14935:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14936:       /* } */
                   14937:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14938:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14939:     }
1.269     brouard  14940: 
1.296     brouard  14941:     /* Prevbcasting */
                   14942:     if(prevbcast==1){
1.219     brouard  14943:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14944:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14945:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14946: 
                   14947:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14948: 
                   14949:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14950: 
1.219     brouard  14951:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14952:       fclose(ficresplb);
                   14953: 
1.222     brouard  14954:       hBijx(p, bage, fage, mobaverage);
                   14955:       fclose(ficrespijb);
1.219     brouard  14956: 
1.296     brouard  14957:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14958:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14959:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14960:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14961:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14962:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14963: 
                   14964:       
1.269     brouard  14965:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14966: 
                   14967:       
1.269     brouard  14968:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14969:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14970:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14971:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14972:     }    /* end  Prevbcasting */
1.268     brouard  14973:  
1.186     brouard  14974:  
                   14975:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14976: 
1.215     brouard  14977:     free_ivector(wav,1,imx);
                   14978:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14979:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14980:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14981:                
                   14982:                
1.127     brouard  14983:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14984:                
1.201     brouard  14985:     strcpy(filerese,"E_");
                   14986:     strcat(filerese,fileresu);
1.126     brouard  14987:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14988:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14989:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14990:     }
1.208     brouard  14991:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14992:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14993: 
                   14994:     pstamp(ficreseij);
1.219     brouard  14995:                
1.351     brouard  14996:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   14997:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  14998:     
1.351     brouard  14999:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   15000:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   15001:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   15002:       /*       continue; */
1.219     brouard  15003:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  15004:       printf("\n#****** ");
1.351     brouard  15005:       for(j=1;j<=cptcovs;j++){
                   15006:       /* for(j=1;j<=cptcoveff;j++) { */
                   15007:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15008:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15009:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15010:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  15011:       }
                   15012:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  15013:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   15014:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  15015:       }
                   15016:       fprintf(ficreseij,"******\n");
1.235     brouard  15017:       printf("******\n");
1.219     brouard  15018:       
                   15019:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15020:       oldm=oldms;savm=savms;
1.330     brouard  15021:       /* 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  15022:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  15023:       
1.219     brouard  15024:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  15025:     }
                   15026:     fclose(ficreseij);
1.208     brouard  15027:     printf("done evsij\n");fflush(stdout);
                   15028:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  15029: 
1.218     brouard  15030:                
1.227     brouard  15031:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  15032:     /* Should be moved in a function */                
1.201     brouard  15033:     strcpy(filerest,"T_");
                   15034:     strcat(filerest,fileresu);
1.127     brouard  15035:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15036:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15037:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15038:     }
1.208     brouard  15039:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15040:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  15041:     strcpy(fileresstde,"STDE_");
                   15042:     strcat(fileresstde,fileresu);
1.126     brouard  15043:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  15044:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15045:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  15046:     }
1.227     brouard  15047:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15048:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  15049: 
1.201     brouard  15050:     strcpy(filerescve,"CVE_");
                   15051:     strcat(filerescve,fileresu);
1.126     brouard  15052:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  15053:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15054:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  15055:     }
1.227     brouard  15056:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15057:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  15058: 
1.201     brouard  15059:     strcpy(fileresv,"V_");
                   15060:     strcat(fileresv,fileresu);
1.126     brouard  15061:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15062:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15063:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15064:     }
1.227     brouard  15065:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15066:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  15067: 
1.235     brouard  15068:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15069:     if (cptcovn < 1){i1=1;}
                   15070:     
1.334     brouard  15071:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15072:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15073:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15074:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15075:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15076:       /* */
                   15077:       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  15078:        continue;
1.350     brouard  15079:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  15080:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15081:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  15082:       /* It might not be a good idea to mix dummies and quantitative */
                   15083:       /* 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 *\/ */
                   15084:       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 */
                   15085:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15086:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15087:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15088:         * (V5 is quanti) V4 and V3 are dummies
                   15089:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15090:         *                                                              l=1 l=2
                   15091:         *                                                           k=1  1   1   0   0
                   15092:         *                                                           k=2  2   1   1   0
                   15093:         *                                                           k=3 [1] [2]  0   1
                   15094:         *                                                           k=4  2   2   1   1
                   15095:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15096:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15097:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15098:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15099:         */
                   15100:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15101:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15102: /* We give up with the combinations!! */
1.342     brouard  15103:        /* if(debugILK) */
                   15104:        /*   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  15105: 
                   15106:        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  15107:          /* 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] */
                   15108:          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  */
                   15109:          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  */
                   15110:          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  15111:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15112:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15113:          }else{
                   15114:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15115:          }
                   15116:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15117:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15118:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15119:          /* For each selected (single) quantitative value */
1.337     brouard  15120:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15121:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15122:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15123:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15124:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15125:          }else{
                   15126:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15127:          }
                   15128:        }else{
                   15129:          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 */
                   15130:          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 */
                   15131:          exit(1);
                   15132:        }
1.335     brouard  15133:       } /* End loop for each variable in the resultline */
1.334     brouard  15134:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15135:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15136:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15137:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15138:       /* }      */
1.208     brouard  15139:       fprintf(ficrest,"******\n");
1.227     brouard  15140:       fprintf(ficlog,"******\n");
                   15141:       printf("******\n");
1.208     brouard  15142:       
                   15143:       fprintf(ficresstdeij,"\n#****** ");
                   15144:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15145:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15146:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15147:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15148:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15149:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15150:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15151:       }
                   15152:       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  15153:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15154:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15155:       }        
1.208     brouard  15156:       fprintf(ficresstdeij,"******\n");
                   15157:       fprintf(ficrescveij,"******\n");
                   15158:       
                   15159:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15160:       /* pstamp(ficresvij); */
1.225     brouard  15161:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15162:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15163:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15164:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15165:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15166:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15167:       }        
1.208     brouard  15168:       fprintf(ficresvij,"******\n");
                   15169:       
                   15170:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15171:       oldm=oldms;savm=savms;
1.235     brouard  15172:       printf(" cvevsij ");
                   15173:       fprintf(ficlog, " cvevsij ");
                   15174:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15175:       printf(" end cvevsij \n ");
                   15176:       fprintf(ficlog, " end cvevsij \n ");
                   15177:       
                   15178:       /*
                   15179:        */
                   15180:       /* goto endfree; */
                   15181:       
                   15182:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15183:       pstamp(ficrest);
                   15184:       
1.269     brouard  15185:       epj=vector(1,nlstate+1);
1.208     brouard  15186:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15187:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15188:        cptcod= 0; /* To be deleted */
                   15189:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15190:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15191:        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  15192:        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 ");
                   15193:        if(vpopbased==1)
                   15194:          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);
                   15195:        else
1.288     brouard  15196:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15197:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15198:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15199:        fprintf(ficrest,"\n");
                   15200:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15201:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15202:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15203:        for(age=bage; age <=fage ;age++){
1.235     brouard  15204:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15205:          if (vpopbased==1) {
                   15206:            if(mobilav ==0){
                   15207:              for(i=1; i<=nlstate;i++)
                   15208:                prlim[i][i]=probs[(int)age][i][k];
                   15209:            }else{ /* mobilav */ 
                   15210:              for(i=1; i<=nlstate;i++)
                   15211:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15212:            }
                   15213:          }
1.219     brouard  15214:          
1.227     brouard  15215:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15216:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15217:          /* printf(" age %4.0f ",age); */
                   15218:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15219:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15220:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15221:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15222:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15223:            }
                   15224:            epj[nlstate+1] +=epj[j];
                   15225:          }
                   15226:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15227:          
1.227     brouard  15228:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15229:            for(j=1;j <=nlstate;j++)
                   15230:              vepp += vareij[i][j][(int)age];
                   15231:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15232:          for(j=1;j <=nlstate;j++){
                   15233:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15234:          }
                   15235:          fprintf(ficrest,"\n");
                   15236:        }
1.208     brouard  15237:       } /* End vpopbased */
1.269     brouard  15238:       free_vector(epj,1,nlstate+1);
1.208     brouard  15239:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15240:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15241:       printf("done selection\n");fflush(stdout);
                   15242:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15243:       
1.335     brouard  15244:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15245: 
                   15246:     printf("done State-specific expectancies\n");fflush(stdout);
                   15247:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15248: 
1.335     brouard  15249:     /* variance-covariance of forward period prevalence */
1.269     brouard  15250:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15251: 
1.227     brouard  15252:     
1.290     brouard  15253:     free_vector(weight,firstobs,lastobs);
1.351     brouard  15254:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  15255:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15256:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15257:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15258:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15259:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15260:     free_ivector(tab,1,NCOVMAX);
                   15261:     fclose(ficresstdeij);
                   15262:     fclose(ficrescveij);
                   15263:     fclose(ficresvij);
                   15264:     fclose(ficrest);
                   15265:     fclose(ficpar);
                   15266:     
                   15267:     
1.126     brouard  15268:     /*---------- End : free ----------------*/
1.219     brouard  15269:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15270:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15271:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15272:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15273:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15274:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15275:   /* endfree:*/
                   15276:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15277:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15278:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15279:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15280:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15281:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15282:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15283:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15284:   free_matrix(matcov,1,npar,1,npar);
                   15285:   free_matrix(hess,1,npar,1,npar);
                   15286:   /*free_vector(delti,1,npar);*/
                   15287:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15288:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15289:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15290:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15291:   
                   15292:   free_ivector(ncodemax,1,NCOVMAX);
                   15293:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15294:   free_ivector(Dummy,-1,NCOVMAX);
                   15295:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15296:   free_ivector(DummyV,-1,NCOVMAX);
                   15297:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15298:   free_ivector(Typevar,-1,NCOVMAX);
                   15299:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15300:   free_ivector(TvarsQ,1,NCOVMAX);
                   15301:   free_ivector(TvarsQind,1,NCOVMAX);
                   15302:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15303:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15304:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15305:   free_ivector(TvarFD,1,NCOVMAX);
                   15306:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15307:   free_ivector(TvarF,1,NCOVMAX);
                   15308:   free_ivector(TvarFind,1,NCOVMAX);
                   15309:   free_ivector(TvarV,1,NCOVMAX);
                   15310:   free_ivector(TvarVind,1,NCOVMAX);
                   15311:   free_ivector(TvarA,1,NCOVMAX);
                   15312:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15313:   free_ivector(TvarFQ,1,NCOVMAX);
                   15314:   free_ivector(TvarFQind,1,NCOVMAX);
                   15315:   free_ivector(TvarVD,1,NCOVMAX);
                   15316:   free_ivector(TvarVDind,1,NCOVMAX);
                   15317:   free_ivector(TvarVQ,1,NCOVMAX);
                   15318:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15319:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15320:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15321:   free_ivector(TvarVVA,1,NCOVMAX);
                   15322:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15323:   free_ivector(TvarVV,1,NCOVMAX);
                   15324:   free_ivector(TvarVVind,1,NCOVMAX);
                   15325:   
1.230     brouard  15326:   free_ivector(Tvarsel,1,NCOVMAX);
                   15327:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15328:   free_ivector(Tposprod,1,NCOVMAX);
                   15329:   free_ivector(Tprod,1,NCOVMAX);
                   15330:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15331:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15332:   free_ivector(Tage,1,NCOVMAX);
                   15333:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15334:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15335:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15336: 
                   15337:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15338: 
1.227     brouard  15339:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15340:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15341:   fflush(fichtm);
                   15342:   fflush(ficgp);
                   15343:   
1.227     brouard  15344:   
1.126     brouard  15345:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15346:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15347:     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  15348:   }else{
                   15349:     printf("End of Imach\n");
                   15350:     fprintf(ficlog,"End of Imach\n");
                   15351:   }
                   15352:   printf("See log file on %s\n",filelog);
                   15353:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15354:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15355:   rend_time = time(NULL);  
                   15356:   end_time = *localtime(&rend_time);
                   15357:   /* tml = *localtime(&end_time.tm_sec); */
                   15358:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15359:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15360:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15361:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15362:   
1.157     brouard  15363:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15364:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15365:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15366:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15367: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15368:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15369:   fclose(fichtm);
                   15370:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15371:   fclose(fichtmcov);
                   15372:   fclose(ficgp);
                   15373:   fclose(ficlog);
                   15374:   /*------ End -----------*/
1.227     brouard  15375:   
1.281     brouard  15376: 
                   15377: /* Executes gnuplot */
1.227     brouard  15378:   
                   15379:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15380: #ifdef WIN32
1.227     brouard  15381:   if (_chdir(pathcd) != 0)
                   15382:     printf("Can't move to directory %s!\n",path);
                   15383:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15384: #else
1.227     brouard  15385:     if(chdir(pathcd) != 0)
                   15386:       printf("Can't move to directory %s!\n", path);
                   15387:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15388: #endif 
1.126     brouard  15389:     printf("Current directory %s!\n",pathcd);
                   15390:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15391:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15392: #ifdef _WIN32
1.126     brouard  15393:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15394: #endif
                   15395:   if(!stat(plotcmd,&info)){
1.158     brouard  15396:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15397:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15398:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15399:     }else
                   15400:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15401: #ifdef __unix
1.126     brouard  15402:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15403:     if(!stat(plotcmd,&info)){
1.158     brouard  15404:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15405:     }else
                   15406:       strcpy(pplotcmd,plotcmd);
                   15407: #endif
                   15408:   }else
                   15409:     strcpy(pplotcmd,plotcmd);
                   15410:   
                   15411:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15412:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15413:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15414:   
1.126     brouard  15415:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15416:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15417:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15418:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15419:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15420:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15421:       strcpy(plotcmd,pplotcmd);
                   15422:     }
1.126     brouard  15423:   }
1.158     brouard  15424:   printf(" Successful, please wait...");
1.126     brouard  15425:   while (z[0] != 'q') {
                   15426:     /* chdir(path); */
1.154     brouard  15427:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15428:     scanf("%s",z);
                   15429: /*     if (z[0] == 'c') system("./imach"); */
                   15430:     if (z[0] == 'e') {
1.158     brouard  15431: #ifdef __APPLE__
1.152     brouard  15432:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15433: #elif __linux
                   15434:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15435: #else
1.152     brouard  15436:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15437: #endif
                   15438:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15439:       system(pplotcmd);
1.126     brouard  15440:     }
                   15441:     else if (z[0] == 'g') system(plotcmd);
                   15442:     else if (z[0] == 'q') exit(0);
                   15443:   }
1.227     brouard  15444: end:
1.126     brouard  15445:   while (z[0] != 'q') {
1.195     brouard  15446:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15447:     scanf("%s",z);
                   15448:   }
1.283     brouard  15449:   printf("End\n");
1.282     brouard  15450:   exit(0);
1.126     brouard  15451: }

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