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

1.361   ! brouard     1: /* $Id: imach.c,v 1.360 2024/04/30 10:59:22 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.360     brouard     3:   $Log: imach.c,v $
1.361   ! brouard     4:   Revision 1.360  2024/04/30 10:59:22  brouard
        !             5:   Summary: Version 0.99s4 and estimation of std of e.j/e..
        !             6: 
1.360     brouard     7:   Revision 1.359  2024/04/24 21:21:17  brouard
                      8:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
                      9: 
1.359     brouard    10:   Revision 1.6  2024/04/24 21:10:29  brouard
                     11:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
1.358     brouard    12: 
1.359     brouard    13:   Revision 1.5  2023/10/09 09:10:01  brouard
                     14:   Summary: trying to reconsider
1.357     brouard    15: 
1.359     brouard    16:   Revision 1.4  2023/06/22 12:50:51  brouard
                     17:   Summary: stil on going
1.357     brouard    18: 
1.359     brouard    19:   Revision 1.3  2023/06/22 11:28:07  brouard
                     20:   *** empty log message ***
1.356     brouard    21: 
1.359     brouard    22:   Revision 1.2  2023/06/22 11:22:40  brouard
                     23:   Summary: with svd but not working yet
1.355     brouard    24: 
1.354     brouard    25:   Revision 1.353  2023/05/08 18:48:22  brouard
                     26:   *** empty log message ***
                     27: 
1.353     brouard    28:   Revision 1.352  2023/04/29 10:46:21  brouard
                     29:   *** empty log message ***
                     30: 
1.352     brouard    31:   Revision 1.351  2023/04/29 10:43:47  brouard
                     32:   Summary: 099r45
                     33: 
1.351     brouard    34:   Revision 1.350  2023/04/24 11:38:06  brouard
                     35:   *** empty log message ***
                     36: 
1.350     brouard    37:   Revision 1.349  2023/01/31 09:19:37  brouard
                     38:   Summary: Improvements in models with age*Vn*Vm
                     39: 
1.348     brouard    40:   Revision 1.347  2022/09/18 14:36:44  brouard
                     41:   Summary: version 0.99r42
                     42: 
1.347     brouard    43:   Revision 1.346  2022/09/16 13:52:36  brouard
                     44:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     45: 
1.346     brouard    46:   Revision 1.345  2022/09/16 13:40:11  brouard
                     47:   Summary: Version 0.99r41
                     48: 
                     49:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     50: 
1.345     brouard    51:   Revision 1.344  2022/09/14 19:33:30  brouard
                     52:   Summary: version 0.99r40
                     53: 
                     54:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     55: 
1.344     brouard    56:   Revision 1.343  2022/09/14 14:22:16  brouard
                     57:   Summary: version 0.99r39
                     58: 
                     59:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     60:   (fixed or time varying), using new last columns of
                     61:   ILK_parameter.txt file.
                     62: 
1.343     brouard    63:   Revision 1.342  2022/09/11 19:54:09  brouard
                     64:   Summary: 0.99r38
                     65: 
                     66:   * imach.c (Module): Adding timevarying products of any kinds,
                     67:   should work before shifting cotvar from ncovcol+nqv columns in
                     68:   order to have a correspondance between the column of cotvar and
                     69:   the id of column.
                     70:   (Module): Some cleaning and adding covariates in ILK.txt
                     71: 
1.342     brouard    72:   Revision 1.341  2022/09/11 07:58:42  brouard
                     73:   Summary: Version 0.99r38
                     74: 
                     75:   After adding change in cotvar.
                     76: 
1.341     brouard    77:   Revision 1.340  2022/09/11 07:53:11  brouard
                     78:   Summary: Version imach 0.99r37
                     79: 
                     80:   * imach.c (Module): Adding timevarying products of any kinds,
                     81:   should work before shifting cotvar from ncovcol+nqv columns in
                     82:   order to have a correspondance between the column of cotvar and
                     83:   the id of column.
                     84: 
1.340     brouard    85:   Revision 1.339  2022/09/09 17:55:22  brouard
                     86:   Summary: version 0.99r37
                     87: 
                     88:   * imach.c (Module): Many improvements for fixing products of fixed
                     89:   timevarying as well as fixed * fixed, and test with quantitative
                     90:   covariate.
                     91: 
1.339     brouard    92:   Revision 1.338  2022/09/04 17:40:33  brouard
                     93:   Summary: 0.99r36
                     94: 
                     95:   * imach.c (Module): Now the easy runs i.e. without result or
                     96:   model=1+age only did not work. The defautl combination should be 1
                     97:   and not 0 because everything hasn't been tranformed yet.
                     98: 
1.338     brouard    99:   Revision 1.337  2022/09/02 14:26:02  brouard
                    100:   Summary: version 0.99r35
                    101: 
                    102:   * src/imach.c: Version 0.99r35 because it outputs same results with
                    103:   1+age+V1+V1*age for females and 1+age for females only
                    104:   (education=1 noweight)
                    105: 
1.337     brouard   106:   Revision 1.336  2022/08/31 09:52:36  brouard
                    107:   *** empty log message ***
                    108: 
1.336     brouard   109:   Revision 1.335  2022/08/31 08:23:16  brouard
                    110:   Summary: improvements...
                    111: 
1.335     brouard   112:   Revision 1.334  2022/08/25 09:08:41  brouard
                    113:   Summary: In progress for quantitative
                    114: 
1.334     brouard   115:   Revision 1.333  2022/08/21 09:10:30  brouard
                    116:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    117:   reassigning covariates: my first idea was that people will always
                    118:   use the first covariate V1 into the model but in fact they are
                    119:   producing data with many covariates and can use an equation model
                    120:   with some of the covariate; it means that in a model V2+V3 instead
                    121:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    122:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    123:   the equation model is restricted to two variables only (V2, V3)
                    124:   and the combination for V2 should be codtabm(k,1) instead of
                    125:   (codtabm(k,2), and the code should be
                    126:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    127:   made. All of these should be simplified once a day like we did in
                    128:   hpxij() for example by using precov[nres] which is computed in
                    129:   decoderesult for each nres of each resultline. Loop should be done
                    130:   on the equation model globally by distinguishing only product with
                    131:   age (which are changing with age) and no more on type of
                    132:   covariates, single dummies, single covariates.
                    133: 
1.333     brouard   134:   Revision 1.332  2022/08/21 09:06:25  brouard
                    135:   Summary: Version 0.99r33
                    136: 
                    137:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    138:   reassigning covariates: my first idea was that people will always
                    139:   use the first covariate V1 into the model but in fact they are
                    140:   producing data with many covariates and can use an equation model
                    141:   with some of the covariate; it means that in a model V2+V3 instead
                    142:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    143:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    144:   the equation model is restricted to two variables only (V2, V3)
                    145:   and the combination for V2 should be codtabm(k,1) instead of
                    146:   (codtabm(k,2), and the code should be
                    147:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    148:   made. All of these should be simplified once a day like we did in
                    149:   hpxij() for example by using precov[nres] which is computed in
                    150:   decoderesult for each nres of each resultline. Loop should be done
                    151:   on the equation model globally by distinguishing only product with
                    152:   age (which are changing with age) and no more on type of
                    153:   covariates, single dummies, single covariates.
                    154: 
1.332     brouard   155:   Revision 1.331  2022/08/07 05:40:09  brouard
                    156:   *** empty log message ***
                    157: 
1.331     brouard   158:   Revision 1.330  2022/08/06 07:18:25  brouard
                    159:   Summary: last 0.99r31
                    160: 
                    161:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    162: 
1.330     brouard   163:   Revision 1.329  2022/08/03 17:29:54  brouard
                    164:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    165: 
1.329     brouard   166:   Revision 1.328  2022/07/27 17:40:48  brouard
                    167:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    168: 
1.328     brouard   169:   Revision 1.327  2022/07/27 14:47:35  brouard
                    170:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    171: 
1.327     brouard   172:   Revision 1.326  2022/07/26 17:33:55  brouard
                    173:   Summary: some test with nres=1
                    174: 
1.326     brouard   175:   Revision 1.325  2022/07/25 14:27:23  brouard
                    176:   Summary: r30
                    177: 
                    178:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    179:   coredumped, revealed by Feiuno, thank you.
                    180: 
1.325     brouard   181:   Revision 1.324  2022/07/23 17:44:26  brouard
                    182:   *** empty log message ***
                    183: 
1.324     brouard   184:   Revision 1.323  2022/07/22 12:30:08  brouard
                    185:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    186: 
1.323     brouard   187:   Revision 1.322  2022/07/22 12:27:48  brouard
                    188:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    189: 
1.322     brouard   190:   Revision 1.321  2022/07/22 12:04:24  brouard
                    191:   Summary: r28
                    192: 
                    193:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    194: 
1.321     brouard   195:   Revision 1.320  2022/06/02 05:10:11  brouard
                    196:   *** empty log message ***
                    197: 
1.320     brouard   198:   Revision 1.319  2022/06/02 04:45:11  brouard
                    199:   * imach.c (Module): Adding the Wald tests from the log to the main
                    200:   htm for better display of the maximum likelihood estimators.
                    201: 
1.319     brouard   202:   Revision 1.318  2022/05/24 08:10:59  brouard
                    203:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    204:   of confidencce intervals with product in the equation modelC
                    205: 
1.318     brouard   206:   Revision 1.317  2022/05/15 15:06:23  brouard
                    207:   * imach.c (Module):  Some minor improvements
                    208: 
1.317     brouard   209:   Revision 1.316  2022/05/11 15:11:31  brouard
                    210:   Summary: r27
                    211: 
1.316     brouard   212:   Revision 1.315  2022/05/11 15:06:32  brouard
                    213:   *** empty log message ***
                    214: 
1.315     brouard   215:   Revision 1.314  2022/04/13 17:43:09  brouard
                    216:   * imach.c (Module): Adding link to text data files
                    217: 
1.314     brouard   218:   Revision 1.313  2022/04/11 15:57:42  brouard
                    219:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    220: 
1.313     brouard   221:   Revision 1.312  2022/04/05 21:24:39  brouard
                    222:   *** empty log message ***
                    223: 
1.312     brouard   224:   Revision 1.311  2022/04/05 21:03:51  brouard
                    225:   Summary: Fixed quantitative covariates
                    226: 
                    227:          Fixed covariates (dummy or quantitative)
                    228:        with missing values have never been allowed but are ERRORS and
                    229:        program quits. Standard deviations of fixed covariates were
                    230:        wrongly computed. Mean and standard deviations of time varying
                    231:        covariates are still not computed.
                    232: 
1.311     brouard   233:   Revision 1.310  2022/03/17 08:45:53  brouard
                    234:   Summary: 99r25
                    235: 
                    236:   Improving detection of errors: result lines should be compatible with
                    237:   the model.
                    238: 
1.310     brouard   239:   Revision 1.309  2021/05/20 12:39:14  brouard
                    240:   Summary: Version 0.99r24
                    241: 
1.309     brouard   242:   Revision 1.308  2021/03/31 13:11:57  brouard
                    243:   Summary: Version 0.99r23
                    244: 
                    245: 
                    246:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    247: 
1.308     brouard   248:   Revision 1.307  2021/03/08 18:11:32  brouard
                    249:   Summary: 0.99r22 fixed bug on result:
                    250: 
1.307     brouard   251:   Revision 1.306  2021/02/20 15:44:02  brouard
                    252:   Summary: Version 0.99r21
                    253: 
                    254:   * imach.c (Module): Fix bug on quitting after result lines!
                    255:   (Module): Version 0.99r21
                    256: 
1.306     brouard   257:   Revision 1.305  2021/02/20 15:28:30  brouard
                    258:   * imach.c (Module): Fix bug on quitting after result lines!
                    259: 
1.305     brouard   260:   Revision 1.304  2021/02/12 11:34:20  brouard
                    261:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    262: 
1.304     brouard   263:   Revision 1.303  2021/02/11 19:50:15  brouard
                    264:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    265: 
1.303     brouard   266:   Revision 1.302  2020/02/22 21:00:05  brouard
                    267:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    268:   and life table from the data without any state)
                    269: 
1.302     brouard   270:   Revision 1.301  2019/06/04 13:51:20  brouard
                    271:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    272: 
1.301     brouard   273:   Revision 1.300  2019/05/22 19:09:45  brouard
                    274:   Summary: version 0.99r19 of May 2019
                    275: 
1.300     brouard   276:   Revision 1.299  2019/05/22 18:37:08  brouard
                    277:   Summary: Cleaned 0.99r19
                    278: 
1.299     brouard   279:   Revision 1.298  2019/05/22 18:19:56  brouard
                    280:   *** empty log message ***
                    281: 
1.298     brouard   282:   Revision 1.297  2019/05/22 17:56:10  brouard
                    283:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    284: 
1.297     brouard   285:   Revision 1.296  2019/05/20 13:03:18  brouard
                    286:   Summary: Projection syntax simplified
                    287: 
                    288: 
                    289:   We can now start projections, forward or backward, from the mean date
                    290:   of inteviews up to or down to a number of years of projection:
                    291:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    292:   or
                    293:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    294:   or
                    295:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    296:   or
                    297:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    298: 
1.296     brouard   299:   Revision 1.295  2019/05/18 09:52:50  brouard
                    300:   Summary: doxygen tex bug
                    301: 
1.295     brouard   302:   Revision 1.294  2019/05/16 14:54:33  brouard
                    303:   Summary: There was some wrong lines added
                    304: 
1.294     brouard   305:   Revision 1.293  2019/05/09 15:17:34  brouard
                    306:   *** empty log message ***
                    307: 
1.293     brouard   308:   Revision 1.292  2019/05/09 14:17:20  brouard
                    309:   Summary: Some updates
                    310: 
1.292     brouard   311:   Revision 1.291  2019/05/09 13:44:18  brouard
                    312:   Summary: Before ncovmax
                    313: 
1.291     brouard   314:   Revision 1.290  2019/05/09 13:39:37  brouard
                    315:   Summary: 0.99r18 unlimited number of individuals
                    316: 
                    317:   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.
                    318: 
1.290     brouard   319:   Revision 1.289  2018/12/13 09:16:26  brouard
                    320:   Summary: Bug for young ages (<-30) will be in r17
                    321: 
1.289     brouard   322:   Revision 1.288  2018/05/02 20:58:27  brouard
                    323:   Summary: Some bugs fixed
                    324: 
1.288     brouard   325:   Revision 1.287  2018/05/01 17:57:25  brouard
                    326:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    327: 
1.287     brouard   328:   Revision 1.286  2018/04/27 14:27:04  brouard
                    329:   Summary: some minor bugs
                    330: 
1.286     brouard   331:   Revision 1.285  2018/04/21 21:02:16  brouard
                    332:   Summary: Some bugs fixed, valgrind tested
                    333: 
1.285     brouard   334:   Revision 1.284  2018/04/20 05:22:13  brouard
                    335:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    336: 
1.284     brouard   337:   Revision 1.283  2018/04/19 14:49:16  brouard
                    338:   Summary: Some minor bugs fixed
                    339: 
1.283     brouard   340:   Revision 1.282  2018/02/27 22:50:02  brouard
                    341:   *** empty log message ***
                    342: 
1.282     brouard   343:   Revision 1.281  2018/02/27 19:25:23  brouard
                    344:   Summary: Adding second argument for quitting
                    345: 
1.281     brouard   346:   Revision 1.280  2018/02/21 07:58:13  brouard
                    347:   Summary: 0.99r15
                    348: 
                    349:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    350: 
1.280     brouard   351:   Revision 1.279  2017/07/20 13:35:01  brouard
                    352:   Summary: temporary working
                    353: 
1.279     brouard   354:   Revision 1.278  2017/07/19 14:09:02  brouard
                    355:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    356: 
1.278     brouard   357:   Revision 1.277  2017/07/17 08:53:49  brouard
                    358:   Summary: BOM files can be read now
                    359: 
1.277     brouard   360:   Revision 1.276  2017/06/30 15:48:31  brouard
                    361:   Summary: Graphs improvements
                    362: 
1.276     brouard   363:   Revision 1.275  2017/06/30 13:39:33  brouard
                    364:   Summary: Saito's color
                    365: 
1.275     brouard   366:   Revision 1.274  2017/06/29 09:47:08  brouard
                    367:   Summary: Version 0.99r14
                    368: 
1.274     brouard   369:   Revision 1.273  2017/06/27 11:06:02  brouard
                    370:   Summary: More documentation on projections
                    371: 
1.273     brouard   372:   Revision 1.272  2017/06/27 10:22:40  brouard
                    373:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    374: 
1.272     brouard   375:   Revision 1.271  2017/06/27 10:17:50  brouard
                    376:   Summary: Some bug with rint
                    377: 
1.271     brouard   378:   Revision 1.270  2017/05/24 05:45:29  brouard
                    379:   *** empty log message ***
                    380: 
1.270     brouard   381:   Revision 1.269  2017/05/23 08:39:25  brouard
                    382:   Summary: Code into subroutine, cleanings
                    383: 
1.269     brouard   384:   Revision 1.268  2017/05/18 20:09:32  brouard
                    385:   Summary: backprojection and confidence intervals of backprevalence
                    386: 
1.268     brouard   387:   Revision 1.267  2017/05/13 10:25:05  brouard
                    388:   Summary: temporary save for backprojection
                    389: 
1.267     brouard   390:   Revision 1.266  2017/05/13 07:26:12  brouard
                    391:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    392: 
1.266     brouard   393:   Revision 1.265  2017/04/26 16:22:11  brouard
                    394:   Summary: imach 0.99r13 Some bugs fixed
                    395: 
1.265     brouard   396:   Revision 1.264  2017/04/26 06:01:29  brouard
                    397:   Summary: Labels in graphs
                    398: 
1.264     brouard   399:   Revision 1.263  2017/04/24 15:23:15  brouard
                    400:   Summary: to save
                    401: 
1.263     brouard   402:   Revision 1.262  2017/04/18 16:48:12  brouard
                    403:   *** empty log message ***
                    404: 
1.262     brouard   405:   Revision 1.261  2017/04/05 10:14:09  brouard
                    406:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    407: 
1.261     brouard   408:   Revision 1.260  2017/04/04 17:46:59  brouard
                    409:   Summary: Gnuplot indexations fixed (humm)
                    410: 
1.260     brouard   411:   Revision 1.259  2017/04/04 13:01:16  brouard
                    412:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    413: 
1.259     brouard   414:   Revision 1.258  2017/04/03 10:17:47  brouard
                    415:   Summary: Version 0.99r12
                    416: 
                    417:   Some cleanings, conformed with updated documentation.
                    418: 
1.258     brouard   419:   Revision 1.257  2017/03/29 16:53:30  brouard
                    420:   Summary: Temp
                    421: 
1.257     brouard   422:   Revision 1.256  2017/03/27 05:50:23  brouard
                    423:   Summary: Temporary
                    424: 
1.256     brouard   425:   Revision 1.255  2017/03/08 16:02:28  brouard
                    426:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    427: 
1.255     brouard   428:   Revision 1.254  2017/03/08 07:13:00  brouard
                    429:   Summary: Fixing data parameter line
                    430: 
1.254     brouard   431:   Revision 1.253  2016/12/15 11:59:41  brouard
                    432:   Summary: 0.99 in progress
                    433: 
1.253     brouard   434:   Revision 1.252  2016/09/15 21:15:37  brouard
                    435:   *** empty log message ***
                    436: 
1.252     brouard   437:   Revision 1.251  2016/09/15 15:01:13  brouard
                    438:   Summary: not working
                    439: 
1.251     brouard   440:   Revision 1.250  2016/09/08 16:07:27  brouard
                    441:   Summary: continue
                    442: 
1.250     brouard   443:   Revision 1.249  2016/09/07 17:14:18  brouard
                    444:   Summary: Starting values from frequencies
                    445: 
1.249     brouard   446:   Revision 1.248  2016/09/07 14:10:18  brouard
                    447:   *** empty log message ***
                    448: 
1.248     brouard   449:   Revision 1.247  2016/09/02 11:11:21  brouard
                    450:   *** empty log message ***
                    451: 
1.247     brouard   452:   Revision 1.246  2016/09/02 08:49:22  brouard
                    453:   *** empty log message ***
                    454: 
1.246     brouard   455:   Revision 1.245  2016/09/02 07:25:01  brouard
                    456:   *** empty log message ***
                    457: 
1.245     brouard   458:   Revision 1.244  2016/09/02 07:17:34  brouard
                    459:   *** empty log message ***
                    460: 
1.244     brouard   461:   Revision 1.243  2016/09/02 06:45:35  brouard
                    462:   *** empty log message ***
                    463: 
1.243     brouard   464:   Revision 1.242  2016/08/30 15:01:20  brouard
                    465:   Summary: Fixing a lots
                    466: 
1.242     brouard   467:   Revision 1.241  2016/08/29 17:17:25  brouard
                    468:   Summary: gnuplot problem in Back projection to fix
                    469: 
1.241     brouard   470:   Revision 1.240  2016/08/29 07:53:18  brouard
                    471:   Summary: Better
                    472: 
1.240     brouard   473:   Revision 1.239  2016/08/26 15:51:03  brouard
                    474:   Summary: Improvement in Powell output in order to copy and paste
                    475: 
                    476:   Author:
                    477: 
1.239     brouard   478:   Revision 1.238  2016/08/26 14:23:35  brouard
                    479:   Summary: Starting tests of 0.99
                    480: 
1.238     brouard   481:   Revision 1.237  2016/08/26 09:20:19  brouard
                    482:   Summary: to valgrind
                    483: 
1.237     brouard   484:   Revision 1.236  2016/08/25 10:50:18  brouard
                    485:   *** empty log message ***
                    486: 
1.236     brouard   487:   Revision 1.235  2016/08/25 06:59:23  brouard
                    488:   *** empty log message ***
                    489: 
1.235     brouard   490:   Revision 1.234  2016/08/23 16:51:20  brouard
                    491:   *** empty log message ***
                    492: 
1.234     brouard   493:   Revision 1.233  2016/08/23 07:40:50  brouard
                    494:   Summary: not working
                    495: 
1.233     brouard   496:   Revision 1.232  2016/08/22 14:20:21  brouard
                    497:   Summary: not working
                    498: 
1.232     brouard   499:   Revision 1.231  2016/08/22 07:17:15  brouard
                    500:   Summary: not working
                    501: 
1.231     brouard   502:   Revision 1.230  2016/08/22 06:55:53  brouard
                    503:   Summary: Not working
                    504: 
1.230     brouard   505:   Revision 1.229  2016/07/23 09:45:53  brouard
                    506:   Summary: Completing for func too
                    507: 
1.229     brouard   508:   Revision 1.228  2016/07/22 17:45:30  brouard
                    509:   Summary: Fixing some arrays, still debugging
                    510: 
1.227     brouard   511:   Revision 1.226  2016/07/12 18:42:34  brouard
                    512:   Summary: temp
                    513: 
1.226     brouard   514:   Revision 1.225  2016/07/12 08:40:03  brouard
                    515:   Summary: saving but not running
                    516: 
1.225     brouard   517:   Revision 1.224  2016/07/01 13:16:01  brouard
                    518:   Summary: Fixes
                    519: 
1.224     brouard   520:   Revision 1.223  2016/02/19 09:23:35  brouard
                    521:   Summary: temporary
                    522: 
1.223     brouard   523:   Revision 1.222  2016/02/17 08:14:50  brouard
                    524:   Summary: Probably last 0.98 stable version 0.98r6
                    525: 
1.222     brouard   526:   Revision 1.221  2016/02/15 23:35:36  brouard
                    527:   Summary: minor bug
                    528: 
1.220     brouard   529:   Revision 1.219  2016/02/15 00:48:12  brouard
                    530:   *** empty log message ***
                    531: 
1.219     brouard   532:   Revision 1.218  2016/02/12 11:29:23  brouard
                    533:   Summary: 0.99 Back projections
                    534: 
1.218     brouard   535:   Revision 1.217  2015/12/23 17:18:31  brouard
                    536:   Summary: Experimental backcast
                    537: 
1.217     brouard   538:   Revision 1.216  2015/12/18 17:32:11  brouard
                    539:   Summary: 0.98r4 Warning and status=-2
                    540: 
                    541:   Version 0.98r4 is now:
                    542:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    543:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    544:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    545: 
1.216     brouard   546:   Revision 1.215  2015/12/16 08:52:24  brouard
                    547:   Summary: 0.98r4 working
                    548: 
1.215     brouard   549:   Revision 1.214  2015/12/16 06:57:54  brouard
                    550:   Summary: temporary not working
                    551: 
1.214     brouard   552:   Revision 1.213  2015/12/11 18:22:17  brouard
                    553:   Summary: 0.98r4
                    554: 
1.213     brouard   555:   Revision 1.212  2015/11/21 12:47:24  brouard
                    556:   Summary: minor typo
                    557: 
1.212     brouard   558:   Revision 1.211  2015/11/21 12:41:11  brouard
                    559:   Summary: 0.98r3 with some graph of projected cross-sectional
                    560: 
                    561:   Author: Nicolas Brouard
                    562: 
1.211     brouard   563:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   564:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   565:   Summary: Adding ftolpl parameter
                    566:   Author: N Brouard
                    567: 
                    568:   We had difficulties to get smoothed confidence intervals. It was due
                    569:   to the period prevalence which wasn't computed accurately. The inner
                    570:   parameter ftolpl is now an outer parameter of the .imach parameter
                    571:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    572:   computation are long.
                    573: 
1.209     brouard   574:   Revision 1.208  2015/11/17 14:31:57  brouard
                    575:   Summary: temporary
                    576: 
1.208     brouard   577:   Revision 1.207  2015/10/27 17:36:57  brouard
                    578:   *** empty log message ***
                    579: 
1.207     brouard   580:   Revision 1.206  2015/10/24 07:14:11  brouard
                    581:   *** empty log message ***
                    582: 
1.206     brouard   583:   Revision 1.205  2015/10/23 15:50:53  brouard
                    584:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    585: 
1.205     brouard   586:   Revision 1.204  2015/10/01 16:20:26  brouard
                    587:   Summary: Some new graphs of contribution to likelihood
                    588: 
1.204     brouard   589:   Revision 1.203  2015/09/30 17:45:14  brouard
                    590:   Summary: looking at better estimation of the hessian
                    591: 
                    592:   Also a better criteria for convergence to the period prevalence And
                    593:   therefore adding the number of years needed to converge. (The
                    594:   prevalence in any alive state shold sum to one
                    595: 
1.203     brouard   596:   Revision 1.202  2015/09/22 19:45:16  brouard
                    597:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    598: 
1.202     brouard   599:   Revision 1.201  2015/09/15 17:34:58  brouard
                    600:   Summary: 0.98r0
                    601: 
                    602:   - Some new graphs like suvival functions
                    603:   - Some bugs fixed like model=1+age+V2.
                    604: 
1.201     brouard   605:   Revision 1.200  2015/09/09 16:53:55  brouard
                    606:   Summary: Big bug thanks to Flavia
                    607: 
                    608:   Even model=1+age+V2. did not work anymore
                    609: 
1.200     brouard   610:   Revision 1.199  2015/09/07 14:09:23  brouard
                    611:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    612: 
1.199     brouard   613:   Revision 1.198  2015/09/03 07:14:39  brouard
                    614:   Summary: 0.98q5 Flavia
                    615: 
1.198     brouard   616:   Revision 1.197  2015/09/01 18:24:39  brouard
                    617:   *** empty log message ***
                    618: 
1.197     brouard   619:   Revision 1.196  2015/08/18 23:17:52  brouard
                    620:   Summary: 0.98q5
                    621: 
1.196     brouard   622:   Revision 1.195  2015/08/18 16:28:39  brouard
                    623:   Summary: Adding a hack for testing purpose
                    624: 
                    625:   After reading the title, ftol and model lines, if the comment line has
                    626:   a q, starting with #q, the answer at the end of the run is quit. It
                    627:   permits to run test files in batch with ctest. The former workaround was
                    628:   $ echo q | imach foo.imach
                    629: 
1.195     brouard   630:   Revision 1.194  2015/08/18 13:32:00  brouard
                    631:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    632: 
1.194     brouard   633:   Revision 1.193  2015/08/04 07:17:42  brouard
                    634:   Summary: 0.98q4
                    635: 
1.193     brouard   636:   Revision 1.192  2015/07/16 16:49:02  brouard
                    637:   Summary: Fixing some outputs
                    638: 
1.192     brouard   639:   Revision 1.191  2015/07/14 10:00:33  brouard
                    640:   Summary: Some fixes
                    641: 
1.191     brouard   642:   Revision 1.190  2015/05/05 08:51:13  brouard
                    643:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    644: 
                    645:   Fix 1+age+.
                    646: 
1.190     brouard   647:   Revision 1.189  2015/04/30 14:45:16  brouard
                    648:   Summary: 0.98q2
                    649: 
1.189     brouard   650:   Revision 1.188  2015/04/30 08:27:53  brouard
                    651:   *** empty log message ***
                    652: 
1.188     brouard   653:   Revision 1.187  2015/04/29 09:11:15  brouard
                    654:   *** empty log message ***
                    655: 
1.187     brouard   656:   Revision 1.186  2015/04/23 12:01:52  brouard
                    657:   Summary: V1*age is working now, version 0.98q1
                    658: 
                    659:   Some codes had been disabled in order to simplify and Vn*age was
                    660:   working in the optimization phase, ie, giving correct MLE parameters,
                    661:   but, as usual, outputs were not correct and program core dumped.
                    662: 
1.186     brouard   663:   Revision 1.185  2015/03/11 13:26:42  brouard
                    664:   Summary: Inclusion of compile and links command line for Intel Compiler
                    665: 
1.185     brouard   666:   Revision 1.184  2015/03/11 11:52:39  brouard
                    667:   Summary: Back from Windows 8. Intel Compiler
                    668: 
1.184     brouard   669:   Revision 1.183  2015/03/10 20:34:32  brouard
                    670:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    671: 
                    672:   We use directest instead of original Powell test; probably no
                    673:   incidence on the results, but better justifications;
                    674:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    675:   wrong results.
                    676: 
1.183     brouard   677:   Revision 1.182  2015/02/12 08:19:57  brouard
                    678:   Summary: Trying to keep directest which seems simpler and more general
                    679:   Author: Nicolas Brouard
                    680: 
1.182     brouard   681:   Revision 1.181  2015/02/11 23:22:24  brouard
                    682:   Summary: Comments on Powell added
                    683: 
                    684:   Author:
                    685: 
1.181     brouard   686:   Revision 1.180  2015/02/11 17:33:45  brouard
                    687:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    688: 
1.180     brouard   689:   Revision 1.179  2015/01/04 09:57:06  brouard
                    690:   Summary: back to OS/X
                    691: 
1.179     brouard   692:   Revision 1.178  2015/01/04 09:35:48  brouard
                    693:   *** empty log message ***
                    694: 
1.178     brouard   695:   Revision 1.177  2015/01/03 18:40:56  brouard
                    696:   Summary: Still testing ilc32 on OSX
                    697: 
1.177     brouard   698:   Revision 1.176  2015/01/03 16:45:04  brouard
                    699:   *** empty log message ***
                    700: 
1.176     brouard   701:   Revision 1.175  2015/01/03 16:33:42  brouard
                    702:   *** empty log message ***
                    703: 
1.175     brouard   704:   Revision 1.174  2015/01/03 16:15:49  brouard
                    705:   Summary: Still in cross-compilation
                    706: 
1.174     brouard   707:   Revision 1.173  2015/01/03 12:06:26  brouard
                    708:   Summary: trying to detect cross-compilation
                    709: 
1.173     brouard   710:   Revision 1.172  2014/12/27 12:07:47  brouard
                    711:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    712: 
1.172     brouard   713:   Revision 1.171  2014/12/23 13:26:59  brouard
                    714:   Summary: Back from Visual C
                    715: 
                    716:   Still problem with utsname.h on Windows
                    717: 
1.171     brouard   718:   Revision 1.170  2014/12/23 11:17:12  brouard
                    719:   Summary: Cleaning some \%% back to %%
                    720: 
                    721:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    722: 
1.170     brouard   723:   Revision 1.169  2014/12/22 23:08:31  brouard
                    724:   Summary: 0.98p
                    725: 
                    726:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    727: 
1.169     brouard   728:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   729:   Summary: update
1.169     brouard   730: 
1.168     brouard   731:   Revision 1.167  2014/12/22 13:50:56  brouard
                    732:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    733: 
                    734:   Testing on Linux 64
                    735: 
1.167     brouard   736:   Revision 1.166  2014/12/22 11:40:47  brouard
                    737:   *** empty log message ***
                    738: 
1.166     brouard   739:   Revision 1.165  2014/12/16 11:20:36  brouard
                    740:   Summary: After compiling on Visual C
                    741: 
                    742:   * imach.c (Module): Merging 1.61 to 1.162
                    743: 
1.165     brouard   744:   Revision 1.164  2014/12/16 10:52:11  brouard
                    745:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    746: 
                    747:   * imach.c (Module): Merging 1.61 to 1.162
                    748: 
1.164     brouard   749:   Revision 1.163  2014/12/16 10:30:11  brouard
                    750:   * imach.c (Module): Merging 1.61 to 1.162
                    751: 
1.163     brouard   752:   Revision 1.162  2014/09/25 11:43:39  brouard
                    753:   Summary: temporary backup 0.99!
                    754: 
1.162     brouard   755:   Revision 1.1  2014/09/16 11:06:58  brouard
                    756:   Summary: With some code (wrong) for nlopt
                    757: 
                    758:   Author:
                    759: 
                    760:   Revision 1.161  2014/09/15 20:41:41  brouard
                    761:   Summary: Problem with macro SQR on Intel compiler
                    762: 
1.161     brouard   763:   Revision 1.160  2014/09/02 09:24:05  brouard
                    764:   *** empty log message ***
                    765: 
1.160     brouard   766:   Revision 1.159  2014/09/01 10:34:10  brouard
                    767:   Summary: WIN32
                    768:   Author: Brouard
                    769: 
1.159     brouard   770:   Revision 1.158  2014/08/27 17:11:51  brouard
                    771:   *** empty log message ***
                    772: 
1.158     brouard   773:   Revision 1.157  2014/08/27 16:26:55  brouard
                    774:   Summary: Preparing windows Visual studio version
                    775:   Author: Brouard
                    776: 
                    777:   In order to compile on Visual studio, time.h is now correct and time_t
                    778:   and tm struct should be used. difftime should be used but sometimes I
                    779:   just make the differences in raw time format (time(&now).
                    780:   Trying to suppress #ifdef LINUX
                    781:   Add xdg-open for __linux in order to open default browser.
                    782: 
1.157     brouard   783:   Revision 1.156  2014/08/25 20:10:10  brouard
                    784:   *** empty log message ***
                    785: 
1.156     brouard   786:   Revision 1.155  2014/08/25 18:32:34  brouard
                    787:   Summary: New compile, minor changes
                    788:   Author: Brouard
                    789: 
1.155     brouard   790:   Revision 1.154  2014/06/20 17:32:08  brouard
                    791:   Summary: Outputs now all graphs of convergence to period prevalence
                    792: 
1.154     brouard   793:   Revision 1.153  2014/06/20 16:45:46  brouard
                    794:   Summary: If 3 live state, convergence to period prevalence on same graph
                    795:   Author: Brouard
                    796: 
1.153     brouard   797:   Revision 1.152  2014/06/18 17:54:09  brouard
                    798:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    799: 
1.152     brouard   800:   Revision 1.151  2014/06/18 16:43:30  brouard
                    801:   *** empty log message ***
                    802: 
1.151     brouard   803:   Revision 1.150  2014/06/18 16:42:35  brouard
                    804:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    805:   Author: brouard
                    806: 
1.150     brouard   807:   Revision 1.149  2014/06/18 15:51:14  brouard
                    808:   Summary: Some fixes in parameter files errors
                    809:   Author: Nicolas Brouard
                    810: 
1.149     brouard   811:   Revision 1.148  2014/06/17 17:38:48  brouard
                    812:   Summary: Nothing new
                    813:   Author: Brouard
                    814: 
                    815:   Just a new packaging for OS/X version 0.98nS
                    816: 
1.148     brouard   817:   Revision 1.147  2014/06/16 10:33:11  brouard
                    818:   *** empty log message ***
                    819: 
1.147     brouard   820:   Revision 1.146  2014/06/16 10:20:28  brouard
                    821:   Summary: Merge
                    822:   Author: Brouard
                    823: 
                    824:   Merge, before building revised version.
                    825: 
1.146     brouard   826:   Revision 1.145  2014/06/10 21:23:15  brouard
                    827:   Summary: Debugging with valgrind
                    828:   Author: Nicolas Brouard
                    829: 
                    830:   Lot of changes in order to output the results with some covariates
                    831:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    832:   improve the code.
                    833:   No more memory valgrind error but a lot has to be done in order to
                    834:   continue the work of splitting the code into subroutines.
                    835:   Also, decodemodel has been improved. Tricode is still not
                    836:   optimal. nbcode should be improved. Documentation has been added in
                    837:   the source code.
                    838: 
1.144     brouard   839:   Revision 1.143  2014/01/26 09:45:38  brouard
                    840:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    841: 
                    842:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    843:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    844: 
1.143     brouard   845:   Revision 1.142  2014/01/26 03:57:36  brouard
                    846:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    847: 
                    848:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    849: 
1.142     brouard   850:   Revision 1.141  2014/01/26 02:42:01  brouard
                    851:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    852: 
1.141     brouard   853:   Revision 1.140  2011/09/02 10:37:54  brouard
                    854:   Summary: times.h is ok with mingw32 now.
                    855: 
1.140     brouard   856:   Revision 1.139  2010/06/14 07:50:17  brouard
                    857:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    858:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    859: 
1.139     brouard   860:   Revision 1.138  2010/04/30 18:19:40  brouard
                    861:   *** empty log message ***
                    862: 
1.138     brouard   863:   Revision 1.137  2010/04/29 18:11:38  brouard
                    864:   (Module): Checking covariates for more complex models
                    865:   than V1+V2. A lot of change to be done. Unstable.
                    866: 
1.137     brouard   867:   Revision 1.136  2010/04/26 20:30:53  brouard
                    868:   (Module): merging some libgsl code. Fixing computation
                    869:   of likelione (using inter/intrapolation if mle = 0) in order to
                    870:   get same likelihood as if mle=1.
                    871:   Some cleaning of code and comments added.
                    872: 
1.136     brouard   873:   Revision 1.135  2009/10/29 15:33:14  brouard
                    874:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    875: 
1.135     brouard   876:   Revision 1.134  2009/10/29 13:18:53  brouard
                    877:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    878: 
1.134     brouard   879:   Revision 1.133  2009/07/06 10:21:25  brouard
                    880:   just nforces
                    881: 
1.133     brouard   882:   Revision 1.132  2009/07/06 08:22:05  brouard
                    883:   Many tings
                    884: 
1.132     brouard   885:   Revision 1.131  2009/06/20 16:22:47  brouard
                    886:   Some dimensions resccaled
                    887: 
1.131     brouard   888:   Revision 1.130  2009/05/26 06:44:34  brouard
                    889:   (Module): Max Covariate is now set to 20 instead of 8. A
                    890:   lot of cleaning with variables initialized to 0. Trying to make
                    891:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    892: 
1.130     brouard   893:   Revision 1.129  2007/08/31 13:49:27  lievre
                    894:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    895: 
1.129     lievre    896:   Revision 1.128  2006/06/30 13:02:05  brouard
                    897:   (Module): Clarifications on computing e.j
                    898: 
1.128     brouard   899:   Revision 1.127  2006/04/28 18:11:50  brouard
                    900:   (Module): Yes the sum of survivors was wrong since
                    901:   imach-114 because nhstepm was no more computed in the age
                    902:   loop. Now we define nhstepma in the age loop.
                    903:   (Module): In order to speed up (in case of numerous covariates) we
                    904:   compute health expectancies (without variances) in a first step
                    905:   and then all the health expectancies with variances or standard
                    906:   deviation (needs data from the Hessian matrices) which slows the
                    907:   computation.
                    908:   In the future we should be able to stop the program is only health
                    909:   expectancies and graph are needed without standard deviations.
                    910: 
1.127     brouard   911:   Revision 1.126  2006/04/28 17:23:28  brouard
                    912:   (Module): Yes the sum of survivors was wrong since
                    913:   imach-114 because nhstepm was no more computed in the age
                    914:   loop. Now we define nhstepma in the age loop.
                    915:   Version 0.98h
                    916: 
1.126     brouard   917:   Revision 1.125  2006/04/04 15:20:31  lievre
                    918:   Errors in calculation of health expectancies. Age was not initialized.
                    919:   Forecasting file added.
                    920: 
                    921:   Revision 1.124  2006/03/22 17:13:53  lievre
                    922:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    923:   The log-likelihood is printed in the log file
                    924: 
                    925:   Revision 1.123  2006/03/20 10:52:43  brouard
                    926:   * imach.c (Module): <title> changed, corresponds to .htm file
                    927:   name. <head> headers where missing.
                    928: 
                    929:   * imach.c (Module): Weights can have a decimal point as for
                    930:   English (a comma might work with a correct LC_NUMERIC environment,
                    931:   otherwise the weight is truncated).
                    932:   Modification of warning when the covariates values are not 0 or
                    933:   1.
                    934:   Version 0.98g
                    935: 
                    936:   Revision 1.122  2006/03/20 09:45:41  brouard
                    937:   (Module): Weights can have a decimal point as for
                    938:   English (a comma might work with a correct LC_NUMERIC environment,
                    939:   otherwise the weight is truncated).
                    940:   Modification of warning when the covariates values are not 0 or
                    941:   1.
                    942:   Version 0.98g
                    943: 
                    944:   Revision 1.121  2006/03/16 17:45:01  lievre
                    945:   * imach.c (Module): Comments concerning covariates added
                    946: 
                    947:   * imach.c (Module): refinements in the computation of lli if
                    948:   status=-2 in order to have more reliable computation if stepm is
                    949:   not 1 month. Version 0.98f
                    950: 
                    951:   Revision 1.120  2006/03/16 15:10:38  lievre
                    952:   (Module): refinements in the computation of lli if
                    953:   status=-2 in order to have more reliable computation if stepm is
                    954:   not 1 month. Version 0.98f
                    955: 
                    956:   Revision 1.119  2006/03/15 17:42:26  brouard
                    957:   (Module): Bug if status = -2, the loglikelihood was
                    958:   computed as likelihood omitting the logarithm. Version O.98e
                    959: 
                    960:   Revision 1.118  2006/03/14 18:20:07  brouard
                    961:   (Module): varevsij Comments added explaining the second
                    962:   table of variances if popbased=1 .
                    963:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    964:   (Module): Function pstamp added
                    965:   (Module): Version 0.98d
                    966: 
                    967:   Revision 1.117  2006/03/14 17:16:22  brouard
                    968:   (Module): varevsij Comments added explaining the second
                    969:   table of variances if popbased=1 .
                    970:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    971:   (Module): Function pstamp added
                    972:   (Module): Version 0.98d
                    973: 
                    974:   Revision 1.116  2006/03/06 10:29:27  brouard
                    975:   (Module): Variance-covariance wrong links and
                    976:   varian-covariance of ej. is needed (Saito).
                    977: 
                    978:   Revision 1.115  2006/02/27 12:17:45  brouard
                    979:   (Module): One freematrix added in mlikeli! 0.98c
                    980: 
                    981:   Revision 1.114  2006/02/26 12:57:58  brouard
                    982:   (Module): Some improvements in processing parameter
                    983:   filename with strsep.
                    984: 
                    985:   Revision 1.113  2006/02/24 14:20:24  brouard
                    986:   (Module): Memory leaks checks with valgrind and:
                    987:   datafile was not closed, some imatrix were not freed and on matrix
                    988:   allocation too.
                    989: 
                    990:   Revision 1.112  2006/01/30 09:55:26  brouard
                    991:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    992: 
                    993:   Revision 1.111  2006/01/25 20:38:18  brouard
                    994:   (Module): Lots of cleaning and bugs added (Gompertz)
                    995:   (Module): Comments can be added in data file. Missing date values
                    996:   can be a simple dot '.'.
                    997: 
                    998:   Revision 1.110  2006/01/25 00:51:50  brouard
                    999:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1000: 
                   1001:   Revision 1.109  2006/01/24 19:37:15  brouard
                   1002:   (Module): Comments (lines starting with a #) are allowed in data.
                   1003: 
                   1004:   Revision 1.108  2006/01/19 18:05:42  lievre
                   1005:   Gnuplot problem appeared...
                   1006:   To be fixed
                   1007: 
                   1008:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1009:   Test existence of gnuplot in imach path
                   1010: 
                   1011:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1012:   Some cleaning and links added in html output
                   1013: 
                   1014:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1015:   *** empty log message ***
                   1016: 
                   1017:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1018:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1019:   (Module): If the status is missing at the last wave but we know
                   1020:   that the person is alive, then we can code his/her status as -2
                   1021:   (instead of missing=-1 in earlier versions) and his/her
                   1022:   contributions to the likelihood is 1 - Prob of dying from last
                   1023:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1024:   the healthy state at last known wave). Version is 0.98
                   1025: 
                   1026:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1027:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1028: 
                   1029:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1030:   Add the possibility to read data file including tab characters.
                   1031: 
                   1032:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1033:   Fix on curr_time
                   1034: 
                   1035:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1036:   Add version for Mac OS X. Just define UNIX in Makefile
                   1037: 
                   1038:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1039:   *** empty log message ***
                   1040: 
                   1041:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1042:   New version 0.97 . First attempt to estimate force of mortality
                   1043:   directly from the data i.e. without the need of knowing the health
                   1044:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1045:   This is the basic analysis of mortality and should be done before any
                   1046:   other analysis, in order to test if the mortality estimated from the
                   1047:   cross-longitudinal survey is different from the mortality estimated
                   1048:   from other sources like vital statistic data.
                   1049: 
                   1050:   The same imach parameter file can be used but the option for mle should be -3.
                   1051: 
1.324     brouard  1052:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1053:   former routines in order to include the new code within the former code.
                   1054: 
                   1055:   The output is very simple: only an estimate of the intercept and of
                   1056:   the slope with 95% confident intervals.
                   1057: 
                   1058:   Current limitations:
                   1059:   A) Even if you enter covariates, i.e. with the
                   1060:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1061:   B) There is no computation of Life Expectancy nor Life Table.
                   1062: 
                   1063:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1064:   Version 0.96d. Population forecasting command line is (temporarily)
                   1065:   suppressed.
                   1066: 
                   1067:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1068:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1069:   rewritten within the same printf. Workaround: many printfs.
                   1070: 
                   1071:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1072:   * imach.c (Repository):
                   1073:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1074:   matrix (cov(a12,c31) instead of numbers.
                   1075: 
                   1076:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1077:   Just cleaning
                   1078: 
                   1079:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1080:   (Module): On windows (cygwin) function asctime_r doesn't
                   1081:   exist so I changed back to asctime which exists.
                   1082:   (Module): Version 0.96b
                   1083: 
                   1084:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1085:   (Module): On windows (cygwin) function asctime_r doesn't
                   1086:   exist so I changed back to asctime which exists.
                   1087: 
                   1088:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1089:   * imach.c (Repository): Duplicated warning errors corrected.
                   1090:   (Repository): Elapsed time after each iteration is now output. It
                   1091:   helps to forecast when convergence will be reached. Elapsed time
                   1092:   is stamped in powell.  We created a new html file for the graphs
                   1093:   concerning matrix of covariance. It has extension -cov.htm.
                   1094: 
                   1095:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1096:   (Module): Some bugs corrected for windows. Also, when
                   1097:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1098:   of the covariance matrix to be input.
                   1099: 
                   1100:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1101:   (Module): Some bugs corrected for windows. Also, when
                   1102:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1103:   of the covariance matrix to be input.
                   1104: 
                   1105:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1106:   * 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.
                   1107: 
                   1108:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1109:   Version 0.96
                   1110: 
                   1111:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1112:   (Module): Change position of html and gnuplot routines and added
                   1113:   routine fileappend.
                   1114: 
                   1115:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1116:   * imach.c (Repository): Check when date of death was earlier that
                   1117:   current date of interview. It may happen when the death was just
                   1118:   prior to the death. In this case, dh was negative and likelihood
                   1119:   was wrong (infinity). We still send an "Error" but patch by
                   1120:   assuming that the date of death was just one stepm after the
                   1121:   interview.
                   1122:   (Repository): Because some people have very long ID (first column)
                   1123:   we changed int to long in num[] and we added a new lvector for
                   1124:   memory allocation. But we also truncated to 8 characters (left
                   1125:   truncation)
                   1126:   (Repository): No more line truncation errors.
                   1127: 
                   1128:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1129:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1130:   place. It differs from routine "prevalence" which may be called
                   1131:   many times. Probs is memory consuming and must be used with
                   1132:   parcimony.
                   1133:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1134: 
                   1135:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1136:   *** empty log message ***
                   1137: 
                   1138:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1139:   Add log in  imach.c and  fullversion number is now printed.
                   1140: 
                   1141: */
                   1142: /*
                   1143:    Interpolated Markov Chain
                   1144: 
                   1145:   Short summary of the programme:
                   1146:   
1.227     brouard  1147:   This program computes Healthy Life Expectancies or State-specific
                   1148:   (if states aren't health statuses) Expectancies from
                   1149:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1150: 
                   1151:   -1- a first survey ("cross") where individuals from different ages
                   1152:   are interviewed on their health status or degree of disability (in
                   1153:   the case of a health survey which is our main interest)
                   1154: 
                   1155:   -2- at least a second wave of interviews ("longitudinal") which
                   1156:   measure each change (if any) in individual health status.  Health
                   1157:   expectancies are computed from the time spent in each health state
                   1158:   according to a model. More health states you consider, more time is
                   1159:   necessary to reach the Maximum Likelihood of the parameters involved
                   1160:   in the model.  The simplest model is the multinomial logistic model
                   1161:   where pij is the probability to be observed in state j at the second
                   1162:   wave conditional to be observed in state i at the first
                   1163:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1164:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1165:   have a more complex model than "constant and age", you should modify
                   1166:   the program where the markup *Covariates have to be included here
                   1167:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1168:   convergence.
                   1169: 
                   1170:   The advantage of this computer programme, compared to a simple
                   1171:   multinomial logistic model, is clear when the delay between waves is not
                   1172:   identical for each individual. Also, if a individual missed an
                   1173:   intermediate interview, the information is lost, but taken into
                   1174:   account using an interpolation or extrapolation.  
                   1175: 
                   1176:   hPijx is the probability to be observed in state i at age x+h
                   1177:   conditional to the observed state i at age x. The delay 'h' can be
                   1178:   split into an exact number (nh*stepm) of unobserved intermediate
                   1179:   states. This elementary transition (by month, quarter,
                   1180:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1181:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1182:   and the contribution of each individual to the likelihood is simply
                   1183:   hPijx.
                   1184: 
                   1185:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1186:   of the life expectancies. It also computes the period (stable) prevalence.
                   1187: 
                   1188: Back prevalence and projections:
1.227     brouard  1189: 
                   1190:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1191:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1192:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1193:    mobilavproj)
                   1194: 
                   1195:     Computes the back prevalence limit for any combination of
                   1196:     covariate values k at any age between ageminpar and agemaxpar and
                   1197:     returns it in **bprlim. In the loops,
                   1198: 
                   1199:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1200:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1201: 
                   1202:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1203:    Computes for any combination of covariates k and any age between bage and fage 
                   1204:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1205:                        oldm=oldms;savm=savms;
1.227     brouard  1206: 
1.267     brouard  1207:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1208:      Computes the transition matrix starting at age 'age' over
                   1209:      'nhstepm*hstepm*stepm' months (i.e. until
                   1210:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1211:      nhstepm*hstepm matrices. 
                   1212: 
                   1213:      Returns p3mat[i][j][h] after calling
                   1214:      p3mat[i][j][h]=matprod2(newm,
                   1215:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1216:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1217:      oldm);
1.226     brouard  1218: 
                   1219: Important routines
                   1220: 
                   1221: - func (or funcone), computes logit (pij) distinguishing
                   1222:   o fixed variables (single or product dummies or quantitative);
                   1223:   o varying variables by:
                   1224:    (1) wave (single, product dummies, quantitative), 
                   1225:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1226:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1227:        % varying dummy (not done) or quantitative (not done);
                   1228: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1229:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1230: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1231:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1232:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1233: 
1.226     brouard  1234: 
                   1235:   
1.324     brouard  1236:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1237:            Institut national d'études démographiques, Paris.
1.126     brouard  1238:   This software have been partly granted by Euro-REVES, a concerted action
                   1239:   from the European Union.
                   1240:   It is copyrighted identically to a GNU software product, ie programme and
                   1241:   software can be distributed freely for non commercial use. Latest version
                   1242:   can be accessed at http://euroreves.ined.fr/imach .
                   1243: 
                   1244:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1245:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1246:   
                   1247:   **********************************************************************/
                   1248: /*
                   1249:   main
                   1250:   read parameterfile
                   1251:   read datafile
                   1252:   concatwav
                   1253:   freqsummary
                   1254:   if (mle >= 1)
                   1255:     mlikeli
                   1256:   print results files
                   1257:   if mle==1 
                   1258:      computes hessian
                   1259:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1260:       begin-prev-date,...
                   1261:   open gnuplot file
                   1262:   open html file
1.145     brouard  1263:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1264:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1265:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1266:     freexexit2 possible for memory heap.
                   1267: 
                   1268:   h Pij x                         | pij_nom  ficrestpij
                   1269:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1270:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1271:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1272: 
                   1273:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1274:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1275:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1276:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1277:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1278: 
1.126     brouard  1279:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1280:   health expectancies
                   1281:   Variance-covariance of DFLE
                   1282:   prevalence()
                   1283:    movingaverage()
                   1284:   varevsij() 
                   1285:   if popbased==1 varevsij(,popbased)
                   1286:   total life expectancies
                   1287:   Variance of period (stable) prevalence
                   1288:  end
                   1289: */
                   1290: 
1.187     brouard  1291: /* #define DEBUG */
                   1292: /* #define DEBUGBRENT */
1.203     brouard  1293: /* #define DEBUGLINMIN */
                   1294: /* #define DEBUGHESS */
                   1295: #define DEBUGHESSIJ
1.224     brouard  1296: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1297: #define POWELL /* Instead of NLOPT */
1.224     brouard  1298: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1299: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1300: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1301: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.359     brouard  1302: /* #define POWELLORIGINCONJUGATE  /\* Don't use conjugate but biggest decrease if valuable *\/ */
                   1303: /* #define NOTMINFIT */
1.126     brouard  1304: 
                   1305: #include <math.h>
                   1306: #include <stdio.h>
                   1307: #include <stdlib.h>
                   1308: #include <string.h>
1.226     brouard  1309: #include <ctype.h>
1.159     brouard  1310: 
                   1311: #ifdef _WIN32
                   1312: #include <io.h>
1.172     brouard  1313: #include <windows.h>
                   1314: #include <tchar.h>
1.159     brouard  1315: #else
1.126     brouard  1316: #include <unistd.h>
1.159     brouard  1317: #endif
1.126     brouard  1318: 
                   1319: #include <limits.h>
                   1320: #include <sys/types.h>
1.171     brouard  1321: 
                   1322: #if defined(__GNUC__)
                   1323: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1324: #endif
                   1325: 
1.126     brouard  1326: #include <sys/stat.h>
                   1327: #include <errno.h>
1.159     brouard  1328: /* extern int errno; */
1.126     brouard  1329: 
1.157     brouard  1330: /* #ifdef LINUX */
                   1331: /* #include <time.h> */
                   1332: /* #include "timeval.h" */
                   1333: /* #else */
                   1334: /* #include <sys/time.h> */
                   1335: /* #endif */
                   1336: 
1.126     brouard  1337: #include <time.h>
                   1338: 
1.136     brouard  1339: #ifdef GSL
                   1340: #include <gsl/gsl_errno.h>
                   1341: #include <gsl/gsl_multimin.h>
                   1342: #endif
                   1343: 
1.167     brouard  1344: 
1.162     brouard  1345: #ifdef NLOPT
                   1346: #include <nlopt.h>
                   1347: typedef struct {
                   1348:   double (* function)(double [] );
                   1349: } myfunc_data ;
                   1350: #endif
                   1351: 
1.126     brouard  1352: /* #include <libintl.h> */
                   1353: /* #define _(String) gettext (String) */
                   1354: 
1.349     brouard  1355: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1356: 
                   1357: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1358: #define GNUPLOTVERSION 5.1
                   1359: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1360: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1361: #define FILENAMELENGTH 256
1.126     brouard  1362: 
                   1363: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1364: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1365: 
1.349     brouard  1366: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1367: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1368: 
                   1369: #define NINTERVMAX 8
1.144     brouard  1370: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1371: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1372: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1373: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1374: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1375: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1376: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1377: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1378: /* #define AGESUP 130 */
1.288     brouard  1379: /* #define AGESUP 150 */
                   1380: #define AGESUP 200
1.268     brouard  1381: #define AGEINF 0
1.218     brouard  1382: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1383: #define AGEBASE 40
1.194     brouard  1384: #define AGEOVERFLOW 1.e20
1.164     brouard  1385: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1386: #ifdef _WIN32
                   1387: #define DIRSEPARATOR '\\'
                   1388: #define CHARSEPARATOR "\\"
                   1389: #define ODIRSEPARATOR '/'
                   1390: #else
1.126     brouard  1391: #define DIRSEPARATOR '/'
                   1392: #define CHARSEPARATOR "/"
                   1393: #define ODIRSEPARATOR '\\'
                   1394: #endif
                   1395: 
1.361   ! brouard  1396: /* $Id: imach.c,v 1.360 2024/04/30 10:59:22 brouard Exp $ */
1.126     brouard  1397: /* $State: Exp $ */
1.196     brouard  1398: #include "version.h"
                   1399: char version[]=__IMACH_VERSION__;
1.360     brouard  1400: char copyright[]="April 2024,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-2024";
1.361   ! brouard  1401: char fullversion[]="$Revision: 1.360 $ $Date: 2024/04/30 10:59:22 $"; 
1.126     brouard  1402: char strstart[80];
                   1403: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1404: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1405: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1406: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1407: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1408: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1409: 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  1410: 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  1411: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1412: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1413: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1414: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1415: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1416: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1417: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1418: 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  1419: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1420: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1421: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1422: 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 */
                   1423: 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 */
                   1424: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1425: 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  1426: int nsd=0; /**< Total number of single dummy variables (output) */
                   1427: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1428: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1429: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1430: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1431: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1432: int cptcov=0; /* Working variable */
1.334     brouard  1433: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1434: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1435: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1436: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1437: int nlstate=2; /* Number of live states */
                   1438: int ndeath=1; /* Number of dead states */
1.130     brouard  1439: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1440: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1441: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1442: int popbased=0;
                   1443: 
                   1444: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1445: int maxwav=0; /* Maxim number of waves */
                   1446: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1447: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
1.359     brouard  1448: int gipmx = 0;
                   1449: double gsw = 0; /* Global variables on the number of contributions
1.126     brouard  1450:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1451: int mle=1, weightopt=0;
1.126     brouard  1452: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1453: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1454: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1455:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1456: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1457: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1458: 
1.130     brouard  1459: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1460: double **matprod2(); /* test */
1.126     brouard  1461: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1462: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1463: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1464: 
1.136     brouard  1465: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1466: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1467: FILE *ficlog, *ficrespow;
1.130     brouard  1468: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1469: double fretone; /* Only one call to likelihood */
1.130     brouard  1470: long ipmx=0; /* Number of contributions */
1.126     brouard  1471: double sw; /* Sum of weights */
                   1472: char filerespow[FILENAMELENGTH];
                   1473: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1474: FILE *ficresilk;
                   1475: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1476: FILE *ficresprobmorprev;
                   1477: FILE *fichtm, *fichtmcov; /* Html File */
                   1478: FILE *ficreseij;
                   1479: char filerese[FILENAMELENGTH];
                   1480: FILE *ficresstdeij;
                   1481: char fileresstde[FILENAMELENGTH];
                   1482: FILE *ficrescveij;
                   1483: char filerescve[FILENAMELENGTH];
                   1484: FILE  *ficresvij;
                   1485: char fileresv[FILENAMELENGTH];
1.269     brouard  1486: 
1.126     brouard  1487: char title[MAXLINE];
1.234     brouard  1488: char model[MAXLINE]; /**< The model line */
1.217     brouard  1489: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1490: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1491: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1492: char command[FILENAMELENGTH];
                   1493: int  outcmd=0;
                   1494: 
1.217     brouard  1495: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1496: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1497: char filelog[FILENAMELENGTH]; /* Log file */
                   1498: char filerest[FILENAMELENGTH];
                   1499: char fileregp[FILENAMELENGTH];
                   1500: char popfile[FILENAMELENGTH];
                   1501: 
                   1502: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1503: 
1.157     brouard  1504: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1505: /* struct timezone tzp; */
                   1506: /* extern int gettimeofday(); */
                   1507: struct tm tml, *gmtime(), *localtime();
                   1508: 
                   1509: extern time_t time();
                   1510: 
                   1511: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1512: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1513: time_t   rlast_btime; /* raw time */
1.157     brouard  1514: struct tm tm;
                   1515: 
1.126     brouard  1516: char strcurr[80], strfor[80];
                   1517: 
                   1518: char *endptr;
                   1519: long lval;
                   1520: double dval;
                   1521: 
                   1522: #define NR_END 1
                   1523: #define FREE_ARG char*
                   1524: #define FTOL 1.0e-10
                   1525: 
                   1526: #define NRANSI 
1.240     brouard  1527: #define ITMAX 200
                   1528: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1529: 
                   1530: #define TOL 2.0e-4 
                   1531: 
                   1532: #define CGOLD 0.3819660 
                   1533: #define ZEPS 1.0e-10 
                   1534: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1535: 
                   1536: #define GOLD 1.618034 
                   1537: #define GLIMIT 100.0 
                   1538: #define TINY 1.0e-20 
                   1539: 
                   1540: static double maxarg1,maxarg2;
                   1541: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1542: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1543:   
                   1544: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1545: #define rint(a) floor(a+0.5)
1.166     brouard  1546: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1547: #define mytinydouble 1.0e-16
1.166     brouard  1548: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1549: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1550: /* static double dsqrarg; */
                   1551: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1552: static double sqrarg;
                   1553: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1554: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1555: int agegomp= AGEGOMP;
                   1556: 
                   1557: int imx; 
                   1558: int stepm=1;
                   1559: /* Stepm, step in month: minimum step interpolation*/
                   1560: 
                   1561: int estepm;
                   1562: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1563: 
                   1564: int m,nb;
                   1565: long *num;
1.197     brouard  1566: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1567: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1568:                   covariate for which somebody answered excluding 
                   1569:                   undefined. Usually 2: 0 and 1. */
                   1570: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1571:                             covariate for which somebody answered including 
                   1572:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1573: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1574: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1575: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1576: 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  1577: double *ageexmed,*agecens;
                   1578: double dateintmean=0;
1.296     brouard  1579:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1580:   double anprojf, mprojf, jprojf;
1.126     brouard  1581: 
1.296     brouard  1582:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1583:   double anbackf, mbackf, jbackf;
                   1584:   double jintmean,mintmean,aintmean;  
1.126     brouard  1585: double *weight;
                   1586: int **s; /* Status */
1.141     brouard  1587: double *agedc;
1.145     brouard  1588: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1589:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1590:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1591: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1592: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1593: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1594: double  idx; 
                   1595: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1596: /* Some documentation */
                   1597:       /*   Design original data
                   1598:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1599:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1600:        *                                                             ntv=3     nqtv=1
1.330     brouard  1601:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1602:        * For time varying covariate, quanti or dummies
                   1603:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1604:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1605:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1606:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1607:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1608:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1609:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1610:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1611:        */
                   1612: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1613: /* 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
                   1614:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1615:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1616: */
1.349     brouard  1617: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1618: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1619: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1620:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1621:                                                                /* product without age, 3 for age and double product   */
                   1622: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1623:                                                                 /*(single or product without age), 2 dummy*/
                   1624:                                                                /* with age product, 3 quant with age product*/
                   1625: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1626: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1627: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1628: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1629: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1630: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1631: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1632: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1633: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1634: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1635: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1636: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1637: /* 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"*/
                   1638: /*  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  1639: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1640: /* 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}*/
                   1641: /* 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  1642: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1643: /* 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  1644: /* 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  1645: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1646: /* Type                    */
                   1647: /* V         1  2  3  4  5 */
                   1648: /*           F  F  V  V  V */
                   1649: /*           D  Q  D  D  Q */
                   1650: /*                         */
                   1651: int *TvarsD;
1.330     brouard  1652: int *TnsdVar;
1.234     brouard  1653: int *TvarsDind;
                   1654: int *TvarsQ;
                   1655: int *TvarsQind;
                   1656: 
1.318     brouard  1657: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1658: int nresult=0;
1.258     brouard  1659: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1660: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1661: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1662: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1663: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1664: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1665: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1666: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1667: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1668: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1669: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1670: 
                   1671: /* 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
                   1672:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1673:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1674: */
1.234     brouard  1675: /* 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  1676: 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 */
                   1677: 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 */
                   1678: 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 */
                   1679: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1680: 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 */
                   1681: 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  1682: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1683: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1684: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1685: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1686: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1687: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1688: 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 */
                   1689: 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  1690: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1691: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1692: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1693: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1694: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1695: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1696:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1697:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1698:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1699:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1700:       /* 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  1701: int *Tvarsel; /**< Selected covariates for output */
                   1702: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1703: 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  1704: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1705: 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  1706: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1707: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1708: int *Tage;
1.227     brouard  1709: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1710: 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  1711: 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*/ 
                   1712: 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  1713: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1714: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1715: int **Tvard;
1.330     brouard  1716: int **Tvardk;
1.227     brouard  1717: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1718: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1719: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1720:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1721:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1722: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1723: double *lsurv, *lpop, *tpop;
                   1724: 
1.231     brouard  1725: #define FD 1; /* Fixed dummy covariate */
                   1726: #define FQ 2; /* Fixed quantitative covariate */
                   1727: #define FP 3; /* Fixed product covariate */
                   1728: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1729: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1730: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1731: #define VD 10; /* Varying dummy covariate */
                   1732: #define VQ 11; /* Varying quantitative covariate */
                   1733: #define VP 12; /* Varying product covariate */
                   1734: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1735: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1736: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1737: #define APFD 16; /* Age product * fixed dummy covariate */
                   1738: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1739: #define APVD 18; /* Age product * varying dummy covariate */
                   1740: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1741: 
                   1742: #define FTYPE 1; /* Fixed covariate */
                   1743: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1744: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1745: 
                   1746: struct kmodel{
                   1747:        int maintype; /* main type */
                   1748:        int subtype; /* subtype */
                   1749: };
                   1750: struct kmodel modell[NCOVMAX];
                   1751: 
1.143     brouard  1752: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1753: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1754: 
                   1755: /**************** split *************************/
                   1756: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1757: {
                   1758:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1759:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1760:   */ 
                   1761:   char *ss;                            /* pointer */
1.186     brouard  1762:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1763: 
                   1764:   l1 = strlen(path );                  /* length of path */
                   1765:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1766:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1767:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1768:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1769:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1770:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1771:     /* get current working directory */
                   1772:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1773: #ifdef WIN32
                   1774:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1775: #else
                   1776:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1777: #endif
1.126     brouard  1778:       return( GLOCK_ERROR_GETCWD );
                   1779:     }
                   1780:     /* got dirc from getcwd*/
                   1781:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1782:   } else {                             /* strip directory from path */
1.126     brouard  1783:     ss++;                              /* after this, the filename */
                   1784:     l2 = strlen( ss );                 /* length of filename */
                   1785:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1786:     strcpy( name, ss );                /* save file name */
                   1787:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1788:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1789:     printf(" DIRC2 = %s \n",dirc);
                   1790:   }
                   1791:   /* We add a separator at the end of dirc if not exists */
                   1792:   l1 = strlen( dirc );                 /* length of directory */
                   1793:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1794:     dirc[l1] =  DIRSEPARATOR;
                   1795:     dirc[l1+1] = 0; 
                   1796:     printf(" DIRC3 = %s \n",dirc);
                   1797:   }
                   1798:   ss = strrchr( name, '.' );           /* find last / */
                   1799:   if (ss >0){
                   1800:     ss++;
                   1801:     strcpy(ext,ss);                    /* save extension */
                   1802:     l1= strlen( name);
                   1803:     l2= strlen(ss)+1;
                   1804:     strncpy( finame, name, l1-l2);
                   1805:     finame[l1-l2]= 0;
                   1806:   }
                   1807: 
                   1808:   return( 0 );                         /* we're done */
                   1809: }
                   1810: 
                   1811: 
                   1812: /******************************************/
                   1813: 
                   1814: void replace_back_to_slash(char *s, char*t)
                   1815: {
                   1816:   int i;
                   1817:   int lg=0;
                   1818:   i=0;
                   1819:   lg=strlen(t);
                   1820:   for(i=0; i<= lg; i++) {
                   1821:     (s[i] = t[i]);
                   1822:     if (t[i]== '\\') s[i]='/';
                   1823:   }
                   1824: }
                   1825: 
1.132     brouard  1826: char *trimbb(char *out, char *in)
1.137     brouard  1827: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1828:   char *s;
                   1829:   s=out;
                   1830:   while (*in != '\0'){
1.137     brouard  1831:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1832:       in++;
                   1833:     }
                   1834:     *out++ = *in++;
                   1835:   }
                   1836:   *out='\0';
                   1837:   return s;
                   1838: }
                   1839: 
1.351     brouard  1840: char *trimbtab(char *out, char *in)
                   1841: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1842:   char *s;
                   1843:   s=out;
                   1844:   while (*in != '\0'){
                   1845:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1846:       in++;
                   1847:     }
                   1848:     *out++ = *in++;
                   1849:   }
                   1850:   *out='\0';
                   1851:   return s;
                   1852: }
                   1853: 
1.187     brouard  1854: /* char *substrchaine(char *out, char *in, char *chain) */
                   1855: /* { */
                   1856: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1857: /*   char *s, *t; */
                   1858: /*   t=in;s=out; */
                   1859: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1860: /*     *out++ = *in++; */
                   1861: /*   } */
                   1862: 
                   1863: /*   /\* *in matches *chain *\/ */
                   1864: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1865: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1866: /*   } */
                   1867: /*   in--; chain--; */
                   1868: /*   while ( (*in != '\0')){ */
                   1869: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1870: /*     *out++ = *in++; */
                   1871: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1872: /*   } */
                   1873: /*   *out='\0'; */
                   1874: /*   out=s; */
                   1875: /*   return out; */
                   1876: /* } */
                   1877: char *substrchaine(char *out, char *in, char *chain)
                   1878: {
                   1879:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1880:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1881: 
                   1882:   char *strloc;
                   1883: 
1.349     brouard  1884:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1885:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1886:   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  1887:   if(strloc != NULL){ 
1.349     brouard  1888:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1889:     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)*/
                   1890:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1891:   }
1.349     brouard  1892:   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  1893:   return out;
                   1894: }
                   1895: 
                   1896: 
1.145     brouard  1897: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1898: {
1.187     brouard  1899:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1900:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1901:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1902:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1903:   */
1.160     brouard  1904:   char *s, *t;
1.145     brouard  1905:   t=in;s=in;
                   1906:   while ((*in != occ) && (*in != '\0')){
                   1907:     *alocc++ = *in++;
                   1908:   }
                   1909:   if( *in == occ){
                   1910:     *(alocc)='\0';
                   1911:     s=++in;
                   1912:   }
                   1913:  
                   1914:   if (s == t) {/* occ not found */
                   1915:     *(alocc-(in-s))='\0';
                   1916:     in=s;
                   1917:   }
                   1918:   while ( *in != '\0'){
                   1919:     *blocc++ = *in++;
                   1920:   }
                   1921: 
                   1922:   *blocc='\0';
                   1923:   return t;
                   1924: }
1.137     brouard  1925: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1926: {
1.187     brouard  1927:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1928:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1929:      gives blocc="abcdef2ghi" and alocc="j".
                   1930:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1931:   */
                   1932:   char *s, *t;
                   1933:   t=in;s=in;
                   1934:   while (*in != '\0'){
                   1935:     while( *in == occ){
                   1936:       *blocc++ = *in++;
                   1937:       s=in;
                   1938:     }
                   1939:     *blocc++ = *in++;
                   1940:   }
                   1941:   if (s == t) /* occ not found */
                   1942:     *(blocc-(in-s))='\0';
                   1943:   else
                   1944:     *(blocc-(in-s)-1)='\0';
                   1945:   in=s;
                   1946:   while ( *in != '\0'){
                   1947:     *alocc++ = *in++;
                   1948:   }
                   1949: 
                   1950:   *alocc='\0';
                   1951:   return s;
                   1952: }
                   1953: 
1.126     brouard  1954: int nbocc(char *s, char occ)
                   1955: {
                   1956:   int i,j=0;
                   1957:   int lg=20;
                   1958:   i=0;
                   1959:   lg=strlen(s);
                   1960:   for(i=0; i<= lg; i++) {
1.234     brouard  1961:     if  (s[i] == occ ) j++;
1.126     brouard  1962:   }
                   1963:   return j;
                   1964: }
                   1965: 
1.349     brouard  1966: int nboccstr(char *textin, char *chain)
                   1967: {
                   1968:   /* Counts the number of occurence of "chain"  in string textin */
                   1969:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1970:   char *strloc;
                   1971:   
                   1972:   int i,j=0;
                   1973: 
                   1974:   i=0;
                   1975: 
                   1976:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1977:   for(;;) {
                   1978:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1979:     if(strloc != NULL){
                   1980:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1981:       j++;
                   1982:     }else
                   1983:       break;
                   1984:   }
                   1985:   return j;
                   1986:   
                   1987: }
1.137     brouard  1988: /* void cutv(char *u,char *v, char*t, char occ) */
                   1989: /* { */
                   1990: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1991: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1992: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1993: /*   int i,lg,j,p=0; */
                   1994: /*   i=0; */
                   1995: /*   lg=strlen(t); */
                   1996: /*   for(j=0; j<=lg-1; j++) { */
                   1997: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1998: /*   } */
1.126     brouard  1999: 
1.137     brouard  2000: /*   for(j=0; j<p; j++) { */
                   2001: /*     (u[j] = t[j]); */
                   2002: /*   } */
                   2003: /*      u[p]='\0'; */
1.126     brouard  2004: 
1.137     brouard  2005: /*    for(j=0; j<= lg; j++) { */
                   2006: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   2007: /*   } */
                   2008: /* } */
1.126     brouard  2009: 
1.160     brouard  2010: #ifdef _WIN32
                   2011: char * strsep(char **pp, const char *delim)
                   2012: {
                   2013:   char *p, *q;
                   2014:          
                   2015:   if ((p = *pp) == NULL)
                   2016:     return 0;
                   2017:   if ((q = strpbrk (p, delim)) != NULL)
                   2018:   {
                   2019:     *pp = q + 1;
                   2020:     *q = '\0';
                   2021:   }
                   2022:   else
                   2023:     *pp = 0;
                   2024:   return p;
                   2025: }
                   2026: #endif
                   2027: 
1.126     brouard  2028: /********************** nrerror ********************/
                   2029: 
                   2030: void nrerror(char error_text[])
                   2031: {
                   2032:   fprintf(stderr,"ERREUR ...\n");
                   2033:   fprintf(stderr,"%s\n",error_text);
                   2034:   exit(EXIT_FAILURE);
                   2035: }
                   2036: /*********************** vector *******************/
                   2037: double *vector(int nl, int nh)
                   2038: {
                   2039:   double *v;
                   2040:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2041:   if (!v) nrerror("allocation failure in vector");
                   2042:   return v-nl+NR_END;
                   2043: }
                   2044: 
                   2045: /************************ free vector ******************/
                   2046: void free_vector(double*v, int nl, int nh)
                   2047: {
                   2048:   free((FREE_ARG)(v+nl-NR_END));
                   2049: }
                   2050: 
                   2051: /************************ivector *******************************/
                   2052: int *ivector(long nl,long nh)
                   2053: {
                   2054:   int *v;
                   2055:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2056:   if (!v) nrerror("allocation failure in ivector");
                   2057:   return v-nl+NR_END;
                   2058: }
                   2059: 
                   2060: /******************free ivector **************************/
                   2061: void free_ivector(int *v, long nl, long nh)
                   2062: {
                   2063:   free((FREE_ARG)(v+nl-NR_END));
                   2064: }
                   2065: 
                   2066: /************************lvector *******************************/
                   2067: long *lvector(long nl,long nh)
                   2068: {
                   2069:   long *v;
                   2070:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2071:   if (!v) nrerror("allocation failure in ivector");
                   2072:   return v-nl+NR_END;
                   2073: }
                   2074: 
                   2075: /******************free lvector **************************/
                   2076: void free_lvector(long *v, long nl, long nh)
                   2077: {
                   2078:   free((FREE_ARG)(v+nl-NR_END));
                   2079: }
                   2080: 
                   2081: /******************* imatrix *******************************/
                   2082: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2083:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2084: { 
                   2085:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2086:   int **m; 
                   2087:   
                   2088:   /* allocate pointers to rows */ 
                   2089:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2090:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2091:   m += NR_END; 
                   2092:   m -= nrl; 
                   2093:   
                   2094:   
                   2095:   /* allocate rows and set pointers to them */ 
                   2096:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2097:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2098:   m[nrl] += NR_END; 
                   2099:   m[nrl] -= ncl; 
                   2100:   
                   2101:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2102:   
                   2103:   /* return pointer to array of pointers to rows */ 
                   2104:   return m; 
                   2105: } 
                   2106: 
                   2107: /****************** free_imatrix *************************/
                   2108: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2109:       int **m;
                   2110:       long nch,ncl,nrh,nrl; 
                   2111:      /* free an int matrix allocated by imatrix() */ 
                   2112: { 
                   2113:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2114:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2115: } 
                   2116: 
                   2117: /******************* matrix *******************************/
                   2118: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2119: {
                   2120:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2121:   double **m;
                   2122: 
                   2123:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2124:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2125:   m += NR_END;
                   2126:   m -= nrl;
                   2127: 
                   2128:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2129:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2130:   m[nrl] += NR_END;
                   2131:   m[nrl] -= ncl;
                   2132: 
                   2133:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2134:   return m;
1.145     brouard  2135:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2136: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2137: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2138:    */
                   2139: }
                   2140: 
                   2141: /*************************free matrix ************************/
                   2142: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2143: {
                   2144:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2145:   free((FREE_ARG)(m+nrl-NR_END));
                   2146: }
                   2147: 
                   2148: /******************* ma3x *******************************/
                   2149: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2150: {
                   2151:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2152:   double ***m;
                   2153: 
                   2154:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2155:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2156:   m += NR_END;
                   2157:   m -= nrl;
                   2158: 
                   2159:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2160:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2161:   m[nrl] += NR_END;
                   2162:   m[nrl] -= ncl;
                   2163: 
                   2164:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2165: 
                   2166:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2167:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2168:   m[nrl][ncl] += NR_END;
                   2169:   m[nrl][ncl] -= nll;
                   2170:   for (j=ncl+1; j<=nch; j++) 
                   2171:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2172:   
                   2173:   for (i=nrl+1; i<=nrh; i++) {
                   2174:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2175:     for (j=ncl+1; j<=nch; j++) 
                   2176:       m[i][j]=m[i][j-1]+nlay;
                   2177:   }
                   2178:   return m; 
                   2179:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2180:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2181:   */
                   2182: }
                   2183: 
                   2184: /*************************free ma3x ************************/
                   2185: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2186: {
                   2187:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2188:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2189:   free((FREE_ARG)(m+nrl-NR_END));
                   2190: }
                   2191: 
                   2192: /*************** function subdirf ***********/
                   2193: char *subdirf(char fileres[])
                   2194: {
                   2195:   /* Caution optionfilefiname is hidden */
                   2196:   strcpy(tmpout,optionfilefiname);
                   2197:   strcat(tmpout,"/"); /* Add to the right */
                   2198:   strcat(tmpout,fileres);
                   2199:   return tmpout;
                   2200: }
                   2201: 
                   2202: /*************** function subdirf2 ***********/
                   2203: char *subdirf2(char fileres[], char *preop)
                   2204: {
1.314     brouard  2205:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2206:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2207:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2208:   /* Caution optionfilefiname is hidden */
                   2209:   strcpy(tmpout,optionfilefiname);
                   2210:   strcat(tmpout,"/");
                   2211:   strcat(tmpout,preop);
                   2212:   strcat(tmpout,fileres);
                   2213:   return tmpout;
                   2214: }
                   2215: 
                   2216: /*************** function subdirf3 ***********/
                   2217: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2218: {
                   2219:   
                   2220:   /* Caution optionfilefiname is hidden */
                   2221:   strcpy(tmpout,optionfilefiname);
                   2222:   strcat(tmpout,"/");
                   2223:   strcat(tmpout,preop);
                   2224:   strcat(tmpout,preop2);
                   2225:   strcat(tmpout,fileres);
                   2226:   return tmpout;
                   2227: }
1.213     brouard  2228:  
                   2229: /*************** function subdirfext ***********/
                   2230: char *subdirfext(char fileres[], char *preop, char *postop)
                   2231: {
                   2232:   
                   2233:   strcpy(tmpout,preop);
                   2234:   strcat(tmpout,fileres);
                   2235:   strcat(tmpout,postop);
                   2236:   return tmpout;
                   2237: }
1.126     brouard  2238: 
1.213     brouard  2239: /*************** function subdirfext3 ***********/
                   2240: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2241: {
                   2242:   
                   2243:   /* Caution optionfilefiname is hidden */
                   2244:   strcpy(tmpout,optionfilefiname);
                   2245:   strcat(tmpout,"/");
                   2246:   strcat(tmpout,preop);
                   2247:   strcat(tmpout,fileres);
                   2248:   strcat(tmpout,postop);
                   2249:   return tmpout;
                   2250: }
                   2251:  
1.162     brouard  2252: char *asc_diff_time(long time_sec, char ascdiff[])
                   2253: {
                   2254:   long sec_left, days, hours, minutes;
                   2255:   days = (time_sec) / (60*60*24);
                   2256:   sec_left = (time_sec) % (60*60*24);
                   2257:   hours = (sec_left) / (60*60) ;
                   2258:   sec_left = (sec_left) %(60*60);
                   2259:   minutes = (sec_left) /60;
                   2260:   sec_left = (sec_left) % (60);
                   2261:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2262:   return ascdiff;
                   2263: }
                   2264: 
1.126     brouard  2265: /***************** f1dim *************************/
                   2266: extern int ncom; 
                   2267: extern double *pcom,*xicom;
                   2268: extern double (*nrfunc)(double []); 
                   2269:  
                   2270: double f1dim(double x) 
                   2271: { 
                   2272:   int j; 
                   2273:   double f;
                   2274:   double *xt; 
                   2275:  
                   2276:   xt=vector(1,ncom); 
                   2277:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2278:   f=(*nrfunc)(xt); 
                   2279:   free_vector(xt,1,ncom); 
                   2280:   return f; 
                   2281: } 
                   2282: 
                   2283: /*****************brent *************************/
                   2284: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2285: {
                   2286:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2287:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2288:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2289:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2290:    * returned function value. 
                   2291:   */
1.126     brouard  2292:   int iter; 
                   2293:   double a,b,d,etemp;
1.159     brouard  2294:   double fu=0,fv,fw,fx;
1.164     brouard  2295:   double ftemp=0.;
1.126     brouard  2296:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2297:   double e=0.0; 
                   2298:  
                   2299:   a=(ax < cx ? ax : cx); 
                   2300:   b=(ax > cx ? ax : cx); 
                   2301:   x=w=v=bx; 
                   2302:   fw=fv=fx=(*f)(x); 
                   2303:   for (iter=1;iter<=ITMAX;iter++) { 
                   2304:     xm=0.5*(a+b); 
                   2305:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2306:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2307:     printf(".");fflush(stdout);
                   2308:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2309: #ifdef DEBUGBRENT
1.126     brouard  2310:     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);
                   2311:     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);
                   2312:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2313: #endif
                   2314:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2315:       *xmin=x; 
                   2316:       return fx; 
                   2317:     } 
                   2318:     ftemp=fu;
                   2319:     if (fabs(e) > tol1) { 
                   2320:       r=(x-w)*(fx-fv); 
                   2321:       q=(x-v)*(fx-fw); 
                   2322:       p=(x-v)*q-(x-w)*r; 
                   2323:       q=2.0*(q-r); 
                   2324:       if (q > 0.0) p = -p; 
                   2325:       q=fabs(q); 
                   2326:       etemp=e; 
                   2327:       e=d; 
                   2328:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2329:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2330:       else { 
1.224     brouard  2331:                                d=p/q; 
                   2332:                                u=x+d; 
                   2333:                                if (u-a < tol2 || b-u < tol2) 
                   2334:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2335:       } 
                   2336:     } else { 
                   2337:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2338:     } 
                   2339:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2340:     fu=(*f)(u); 
                   2341:     if (fu <= fx) { 
                   2342:       if (u >= x) a=x; else b=x; 
                   2343:       SHFT(v,w,x,u) 
1.183     brouard  2344:       SHFT(fv,fw,fx,fu) 
                   2345:     } else { 
                   2346:       if (u < x) a=u; else b=u; 
                   2347:       if (fu <= fw || w == x) { 
1.224     brouard  2348:                                v=w; 
                   2349:                                w=u; 
                   2350:                                fv=fw; 
                   2351:                                fw=fu; 
1.183     brouard  2352:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2353:                                v=u; 
                   2354:                                fv=fu; 
1.183     brouard  2355:       } 
                   2356:     } 
1.126     brouard  2357:   } 
                   2358:   nrerror("Too many iterations in brent"); 
                   2359:   *xmin=x; 
                   2360:   return fx; 
                   2361: } 
                   2362: 
                   2363: /****************** mnbrak ***********************/
                   2364: 
                   2365: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2366:            double (*func)(double)) 
1.183     brouard  2367: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2368: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2369: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2370: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2371:    */
1.126     brouard  2372:   double ulim,u,r,q, dum;
                   2373:   double fu; 
1.187     brouard  2374: 
                   2375:   double scale=10.;
                   2376:   int iterscale=0;
                   2377: 
                   2378:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2379:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2380: 
                   2381: 
                   2382:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2383:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2384:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2385:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2386:   /* } */
                   2387: 
1.126     brouard  2388:   if (*fb > *fa) { 
                   2389:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2390:     SHFT(dum,*fb,*fa,dum) 
                   2391:   } 
1.126     brouard  2392:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2393:   *fc=(*func)(*cx); 
1.183     brouard  2394: #ifdef DEBUG
1.224     brouard  2395:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2396:   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  2397: #endif
1.224     brouard  2398:   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  2399:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2400:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2401:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2402:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2403:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2404:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2405:       fu=(*func)(u); 
1.163     brouard  2406: #ifdef DEBUG
                   2407:       /* f(x)=A(x-u)**2+f(u) */
                   2408:       double A, fparabu; 
                   2409:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2410:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2411:       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);
                   2412:       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  2413:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2414:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2415:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2416:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2417: #endif 
1.184     brouard  2418: #ifdef MNBRAKORIGINAL
1.183     brouard  2419: #else
1.191     brouard  2420: /*       if (fu > *fc) { */
                   2421: /* #ifdef DEBUG */
                   2422: /*       printf("mnbrak4  fu > fc \n"); */
                   2423: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2424: /* #endif */
                   2425: /*     /\* 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 *\\/  *\/ */
                   2426: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2427: /*     dum=u; /\* Shifting c and u *\/ */
                   2428: /*     u = *cx; */
                   2429: /*     *cx = dum; */
                   2430: /*     dum = fu; */
                   2431: /*     fu = *fc; */
                   2432: /*     *fc =dum; */
                   2433: /*       } else { /\* end *\/ */
                   2434: /* #ifdef DEBUG */
                   2435: /*       printf("mnbrak3  fu < fc \n"); */
                   2436: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2437: /* #endif */
                   2438: /*     dum=u; /\* Shifting c and u *\/ */
                   2439: /*     u = *cx; */
                   2440: /*     *cx = dum; */
                   2441: /*     dum = fu; */
                   2442: /*     fu = *fc; */
                   2443: /*     *fc =dum; */
                   2444: /*       } */
1.224     brouard  2445: #ifdef DEBUGMNBRAK
                   2446:                 double A, fparabu; 
                   2447:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2448:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2449:      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);
                   2450:      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  2451: #endif
1.191     brouard  2452:       dum=u; /* Shifting c and u */
                   2453:       u = *cx;
                   2454:       *cx = dum;
                   2455:       dum = fu;
                   2456:       fu = *fc;
                   2457:       *fc =dum;
1.183     brouard  2458: #endif
1.162     brouard  2459:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2460: #ifdef DEBUG
1.224     brouard  2461:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2462:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2463: #endif
1.126     brouard  2464:       fu=(*func)(u); 
                   2465:       if (fu < *fc) { 
1.183     brouard  2466: #ifdef DEBUG
1.224     brouard  2467:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2468:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2469: #endif
                   2470:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2471:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2472: #ifdef DEBUG
                   2473:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2474: #endif
                   2475:       } 
1.162     brouard  2476:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2477: #ifdef DEBUG
1.224     brouard  2478:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2479:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2480: #endif
1.126     brouard  2481:       u=ulim; 
                   2482:       fu=(*func)(u); 
1.183     brouard  2483:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2484: #ifdef DEBUG
1.224     brouard  2485:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2486:       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  2487: #endif
1.126     brouard  2488:       u=(*cx)+GOLD*(*cx-*bx); 
                   2489:       fu=(*func)(u); 
1.224     brouard  2490: #ifdef DEBUG
                   2491:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2492:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2493: #endif
1.183     brouard  2494:     } /* end tests */
1.126     brouard  2495:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2496:     SHFT(*fa,*fb,*fc,fu) 
                   2497: #ifdef DEBUG
1.224     brouard  2498:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2499:       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  2500: #endif
                   2501:   } /* 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  2502: } 
                   2503: 
                   2504: /*************** linmin ************************/
1.162     brouard  2505: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2506: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2507: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2508: the value of func at the returned location p . This is actually all accomplished by calling the
                   2509: routines mnbrak and brent .*/
1.126     brouard  2510: int ncom; 
                   2511: double *pcom,*xicom;
                   2512: double (*nrfunc)(double []); 
                   2513:  
1.224     brouard  2514: #ifdef LINMINORIGINAL
1.126     brouard  2515: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2516: #else
                   2517: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2518: #endif
1.126     brouard  2519: { 
                   2520:   double brent(double ax, double bx, double cx, 
                   2521:               double (*f)(double), double tol, double *xmin); 
                   2522:   double f1dim(double x); 
                   2523:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2524:              double *fc, double (*func)(double)); 
                   2525:   int j; 
                   2526:   double xx,xmin,bx,ax; 
                   2527:   double fx,fb,fa;
1.187     brouard  2528: 
1.203     brouard  2529: #ifdef LINMINORIGINAL
                   2530: #else
                   2531:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2532: #endif
                   2533:   
1.126     brouard  2534:   ncom=n; 
                   2535:   pcom=vector(1,n); 
                   2536:   xicom=vector(1,n); 
                   2537:   nrfunc=func; 
                   2538:   for (j=1;j<=n;j++) { 
                   2539:     pcom[j]=p[j]; 
1.202     brouard  2540:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2541:   } 
1.187     brouard  2542: 
1.203     brouard  2543: #ifdef LINMINORIGINAL
                   2544:   xx=1.;
                   2545: #else
                   2546:   axs=0.0;
                   2547:   xxs=1.;
                   2548:   do{
                   2549:     xx= xxs;
                   2550: #endif
1.187     brouard  2551:     ax=0.;
                   2552:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2553:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2554:     /* 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))   */
                   2555:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2556:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2557:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2558:     /* 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  2559: #ifdef LINMINORIGINAL
                   2560: #else
                   2561:     if (fx != fx){
1.224     brouard  2562:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2563:                        printf("|");
                   2564:                        fprintf(ficlog,"|");
1.203     brouard  2565: #ifdef DEBUGLINMIN
1.224     brouard  2566:                        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  2567: #endif
                   2568:     }
1.224     brouard  2569:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2570: #endif
                   2571:   
1.191     brouard  2572: #ifdef DEBUGLINMIN
                   2573:   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  2574:   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  2575: #endif
1.224     brouard  2576: #ifdef LINMINORIGINAL
                   2577: #else
1.317     brouard  2578:   if(fb == fx){ /* Flat function in the direction */
                   2579:     xmin=xx;
1.224     brouard  2580:     *flat=1;
1.317     brouard  2581:   }else{
1.224     brouard  2582:     *flat=0;
                   2583: #endif
                   2584:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2585:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2586:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2587:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2588:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2589:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2590: #ifdef DEBUG
1.224     brouard  2591:   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);
                   2592:   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);
                   2593: #endif
                   2594: #ifdef LINMINORIGINAL
                   2595: #else
                   2596:                        }
1.126     brouard  2597: #endif
1.191     brouard  2598: #ifdef DEBUGLINMIN
                   2599:   printf("linmin end ");
1.202     brouard  2600:   fprintf(ficlog,"linmin end ");
1.191     brouard  2601: #endif
1.126     brouard  2602:   for (j=1;j<=n;j++) { 
1.203     brouard  2603: #ifdef LINMINORIGINAL
                   2604:     xi[j] *= xmin; 
                   2605: #else
                   2606: #ifdef DEBUGLINMIN
                   2607:     if(xxs <1.0)
                   2608:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2609: #endif
                   2610:     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) */
                   2611: #ifdef DEBUGLINMIN
                   2612:     if(xxs <1.0)
                   2613:       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 );
                   2614: #endif
                   2615: #endif
1.187     brouard  2616:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2617:   } 
1.191     brouard  2618: #ifdef DEBUGLINMIN
1.203     brouard  2619:   printf("\n");
1.191     brouard  2620:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2621:   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  2622:   for (j=1;j<=n;j++) { 
1.202     brouard  2623:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2624:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2625:     if(j % ncovmodel == 0){
1.191     brouard  2626:       printf("\n");
1.202     brouard  2627:       fprintf(ficlog,"\n");
                   2628:     }
1.191     brouard  2629:   }
1.203     brouard  2630: #else
1.191     brouard  2631: #endif
1.126     brouard  2632:   free_vector(xicom,1,n); 
                   2633:   free_vector(pcom,1,n); 
                   2634: } 
                   2635: 
1.359     brouard  2636: /**** praxis gegen ****/
                   2637: 
                   2638: /* This has been tested by Visual C from Microsoft and works */
                   2639: /* meaning tha valgrind could be wrong */
                   2640: /*********************************************************************/
                   2641: /*     f u n c t i o n     p r a x i s                              */
                   2642: /*                                                                   */
                   2643: /* praxis is a general purpose routine for the minimization of a     */
                   2644: /* function in several variables. the algorithm used is a modifi-    */
                   2645: /* cation of conjugate gradient search method by powell. the changes */
                   2646: /* are due to r.p. brent, who gives an algol-w program, which served */
                   2647: /* as a basis for this function.                                     */
                   2648: /*                                                                   */
                   2649: /* references:                                                       */
                   2650: /*     - powell, m.j.d., 1964. an efficient method for finding       */
                   2651: /*       the minimum of a function in several variables without      */
                   2652: /*       calculating derivatives, computer journal, 7, 155-162       */
                   2653: /*     - brent, r.p., 1973. algorithms for minimization without      */
                   2654: /*       derivatives, prentice hall, englewood cliffs.               */
                   2655: /*                                                                   */
                   2656: /*     problems, suggestions or improvements are always wellcome     */
                   2657: /*                       karl gegenfurtner   07/08/87                */
                   2658: /*                                           c - version             */
                   2659: /*********************************************************************/
                   2660: /*                                                                   */
                   2661: /* usage: min = praxis(tol, macheps, h, n, prin, x, func)      */
                   2662: /* macheps has been suppressed because it is replaced by DBL_EPSILON */
                   2663: /* and if it was an argument of praxis (as it is in original brent)  */
                   2664: /* it should be declared external */
                   2665: /* usage: min = praxis(tol, h, n, prin, x, func)      */
                   2666: /* was    min = praxis(fun, x, n);                                   */
                   2667: /*                                                                   */
                   2668: /*  fun        the function to be minimized. fun is called from      */
                   2669: /*             praxis with x and n as arguments                      */
                   2670: /*  x          a double array containing the initial guesses for     */
                   2671: /*             the minimum, which will contain the solution on       */
                   2672: /*             return                                                */
                   2673: /*  n          an integer specifying the number of unknown           */
                   2674: /*             parameters                                            */
                   2675: /*  min        praxis returns the least calculated value of fun      */
                   2676: /*                                                                   */
                   2677: /* some additional global variables control some more aspects of     */
                   2678: /* the inner workings of praxis. setting them is optional, they      */
                   2679: /* are all set to some reasonable default values given below.        */
                   2680: /*                                                                   */
                   2681: /*   prin      controls the printed output from the routine.         */
                   2682: /*             0 -> no output                                        */
                   2683: /*             1 -> print only starting and final values             */
                   2684: /*             2 -> detailed map of the minimization process         */
                   2685: /*             3 -> print also eigenvalues and vectors of the        */
                   2686: /*                  search directions                                */
                   2687: /*             the default value is 1                                */
                   2688: /*  tol        is the tolerance allowed for the precision of the     */
                   2689: /*             solution. praxis returns if the criterion             */
                   2690: /*             2 * ||x[k]-x[k-1]|| <= sqrt(macheps) * ||x[k]|| + tol */
                   2691: /*             is fulfilled more than ktm times.                     */
                   2692: /*             the default value depends on the machine precision    */
                   2693: /*  ktm        see just above. default is 1, and a value of 4 leads  */
                   2694: /*             to a very(!) cautious stopping criterion.             */
                   2695: /*  h0 or step       is a steplength parameter and should be set equal     */
                   2696: /*             to the expected distance from the solution.           */
                   2697: /*             exceptionally small or large values of step lead to   */
                   2698: /*             slower convergence on the first few iterations        */
                   2699: /*             the default value for step is 1.0                     */
                   2700: /*  scbd       is a scaling parameter. 1.0 is the default and        */
                   2701: /*             indicates no scaling. if the scales for the different */
                   2702: /*             parameters are very different, scbd should be set to  */
                   2703: /*             a value of about 10.0.                                */
                   2704: /*  illc       should be set to true (1) if the problem is known to  */
                   2705: /*             be ill-conditioned. the default is false (0). this    */
                   2706: /*             variable is automatically set, when praxis finds      */
                   2707: /*             the problem to be ill-conditioned during iterations.  */
                   2708: /*  maxfun     is the maximum number of calls to fun allowed. praxis */
                   2709: /*             will return after maxfun calls to fun even when the   */
                   2710: /*             minimum is not yet found. the default value of 0      */
                   2711: /*             indicates no limit on the number of calls.            */
                   2712: /*             this return condition is only checked every n         */
                   2713: /*             iterations.                                           */
                   2714: /*                                                                   */
                   2715: /*********************************************************************/
                   2716: 
                   2717: #include <math.h>
                   2718: #include <stdio.h>
                   2719: #include <stdlib.h>
                   2720: #include <float.h> /* for DBL_EPSILON */
                   2721: /* #include "machine.h" */
                   2722: 
                   2723: 
                   2724: /* extern void minfit(int n, double eps, double tol, double **ab, double q[]); */
                   2725: /* extern void minfit(int n, double eps, double tol, double ab[N][N], double q[]); */
                   2726: /* control parameters */
                   2727: /* control parameters */
                   2728: #define SQREPSILON 1.0e-19
                   2729: /* #define EPSILON 1.0e-8 */ /* in main */
                   2730: 
                   2731: double tol = SQREPSILON,
                   2732:        scbd = 1.0,
                   2733:        step = 1.0;
                   2734: int    ktm = 1,
                   2735:        /* prin = 2, */
                   2736:        maxfun = 0,
                   2737:        illc = 0;
                   2738:        
                   2739: /* some global variables */
                   2740: static int i, j, k, k2, nl, nf, kl, kt;
                   2741: /* static double s; */
                   2742: double sl, dn, dmin,
                   2743:        fx, f1, lds, ldt, sf, df,
                   2744:        qf1, qd0, qd1, qa, qb, qc,
                   2745:        m2, m4, small_windows, vsmall, large, 
                   2746:        vlarge, ldfac, t2;
                   2747: /* static double d[N], y[N], z[N], */
                   2748: /*        q0[N], q1[N], v[N][N]; */
                   2749: 
                   2750: static double *d, *y, *z;
                   2751: static double  *q0, *q1, **v;
                   2752: double *tflin; /* used in flin: return (*fun)(tflin, n); */
                   2753: double *e; /* used in minfit, don't konw how to free memory and thus made global */
                   2754: /* static double s, sl, dn, dmin, */
                   2755: /*        fx, f1, lds, ldt, sf, df, */
                   2756: /*        qf1, qd0, qd1, qa, qb, qc, */
                   2757: /*        m2, m4, small, vsmall, large,  */
                   2758: /*        vlarge, ldfac, t2; */
                   2759: /* static double d[N], y[N], z[N], */
                   2760: /*        q0[N], q1[N], v[N][N]; */
                   2761: 
                   2762: /* these will be set by praxis to point to it's arguments */
                   2763: static int prin; /* added */
                   2764: static int n;
                   2765: static double *x;
                   2766: static double (*fun)();
                   2767: /* static double (*fun)(double *x, int n); */
                   2768: 
                   2769: /* these will be set by praxis to the global control parameters */
                   2770: /* static double h, macheps, t; */
                   2771: extern double macheps;
                   2772: static double h;
                   2773: static double t;
                   2774: 
                   2775: static double 
                   2776: drandom()      /* return random no between 0 and 1 */
                   2777: {
                   2778:    return (double)(rand()%(8192*2))/(double)(8192*2);
                   2779: }
                   2780: 
                   2781: static void sort()             /* d and v in descending order */
                   2782: {
                   2783:    int k, i, j;
                   2784:    double s;
                   2785: 
                   2786:    for (i=1; i<=n-1; i++) {
                   2787:        k = i; s = d[i];
                   2788:        for (j=i+1; j<=n; j++) {
                   2789:            if (d[j] > s) {
                   2790:              k = j;
                   2791:              s = d[j];
                   2792:           }
                   2793:        }
                   2794:        if (k > i) {
                   2795:          d[k] = d[i];
                   2796:          d[i] = s;
                   2797:          for (j=1; j<=n; j++) {
                   2798:              s = v[j][i];
                   2799:              v[j][i] = v[j][k];
                   2800:              v[j][k] = s;
                   2801:          }
                   2802:        }
                   2803:    }
                   2804: }
                   2805: 
                   2806: double randbrent ( int *naught )
                   2807: {
                   2808:   double ran1, ran3[127], half;
                   2809:   int ran2, q, r, i, j;
                   2810:   int init=0; /* false */
                   2811:   double rr;
                   2812:   /* REAL*8 RAN1,RAN3(127),HALF */
                   2813: 
                   2814:   /*     INTEGER RAN2,Q,R */
                   2815:   /*     LOGICAL INIT */
                   2816:   /*     DATA INIT/.FALSE./ */
                   2817:   /*     IF (INIT) GO TO 3 */
                   2818:   if(!init){ 
                   2819: /*       R = MOD(NAUGHT,8190) + 1 *//* 1804289383 rand () */
                   2820:     r = *naught % 8190 + 1;/* printf(" naught r %d %d",*naught,r); */
                   2821:     ran2=127;
                   2822:     for(i=ran2; i>0; i--){
                   2823: /*       RAN2 = 128 */
                   2824: /*       DO 2 I=1,127 */
                   2825:       ran2 = ran2-1;
                   2826: /*          RAN2 = RAN2 - 1 */
                   2827:       ran1 = -pow(2.0,55);
                   2828: /*          RAN1 = -2.D0**55 */
                   2829: /*          DO 1 J=1,7 */
                   2830:       for(j=1; j<=7;j++){
                   2831: /*             R = MOD(1756*R,8191) */
                   2832:        r = (1756*r) % 8191;/* printf(" i=%d (1756*r)%8191=%d",j,r); */
                   2833:        q=r/32;
                   2834: /*             Q = R/32 */
                   2835: /* 1           RAN1 = (RAN1 + Q)*(1.0D0/256) */
                   2836:        ran1 =(ran1+q)*(1.0/256);
                   2837:       }
                   2838: /* 2        RAN3(RAN2) = RAN1 */
                   2839:       ran3[ran2] = ran1; /* printf(" ran2=%d ran1=%.7g \n",ran2,ran1); */ 
                   2840:     }
                   2841: /*       INIT = .TRUE. */
                   2842:     init=1;
                   2843: /* 3     IF (RAN2.EQ.1) RAN2 = 128 */
                   2844:   }
                   2845:   if(ran2 == 0) ran2 = 126;
                   2846:   else ran2 = ran2 -1;
                   2847:   /* RAN2 = RAN2 - 1 */
                   2848:   /* RAN1 = RAN1 + RAN3(RAN2) */
                   2849:   ran1 = ran1 + ran3[ran2];/* printf("BIS ran2=%d ran1=%.7g \n",ran2,ran1);  */
                   2850:   half= 0.5;
                   2851:   /* HALF = .5D0 */
                   2852:   /* IF (RAN1.GE.0.D0) HALF = -HALF */
                   2853:   if(ran1 >= 0.) half =-half;
                   2854:   ran1 = ran1 +half;
                   2855:   ran3[ran2] = ran1;
                   2856:   rr= ran1+0.5;
                   2857:   /* RAN1 = RAN1 + HALF */
                   2858:   /*   RAN3(RAN2) = RAN1 */
                   2859:   /*   RANDOM = RAN1 + .5D0 */
                   2860: /*   r = ( ( double ) ( *seed ) ) * 4.656612875E-10; */
                   2861:   return rr;
                   2862: }
                   2863: static void matprint(char *s, double **v, int m, int n)
                   2864: /* char *s; */
                   2865: /* double v[N][N]; */
                   2866: {
                   2867: #define INCX 8
                   2868:   int i;
                   2869:  
                   2870:   int i2hi;
                   2871:   int ihi;
                   2872:   int ilo;
                   2873:   int i2lo;
                   2874:   int jlo=1;
                   2875:   int j;
                   2876:   int j2hi;
                   2877:   int jhi;
                   2878:   int j2lo;
                   2879:   ilo=1;
                   2880:   ihi=n;
                   2881:   jlo=1;
                   2882:   jhi=n;
                   2883:   
                   2884:   printf ("\n" );
                   2885:   printf ("%s\n", s );
                   2886:   for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
                   2887:   {
                   2888:     j2hi = j2lo + INCX - 1;
                   2889:     if ( n < j2hi )
                   2890:     {
                   2891:       j2hi = n;
                   2892:     }
                   2893:     if ( jhi < j2hi )
                   2894:     {
                   2895:       j2hi = jhi;
                   2896:     }
                   2897: 
                   2898:     /* fprintf ( ficlog, "\n" ); */
                   2899:     printf ("\n" );
                   2900: /*
                   2901:   For each column J in the current range...
                   2902: 
                   2903:   Write the header.
                   2904: */
                   2905:     /* fprintf ( ficlog, "  Col:  "); */
                   2906:     printf ("Col:");
                   2907:     for ( j = j2lo; j <= j2hi; j++ )
                   2908:     {
                   2909:       /* fprintf ( ficlog, "  %7d     ", j - 1 ); */
                   2910:       /* printf (" %9d      ", j - 1 ); */
                   2911:       printf (" %9d      ", j );
                   2912:     }
                   2913:     /* fprintf ( ficlog, "\n" ); */
                   2914:     /* fprintf ( ficlog, "  Row\n" ); */
                   2915:     /* fprintf ( ficlog, "\n" ); */
                   2916:     printf ("\n" );
                   2917:     printf ("  Row\n" );
                   2918:     printf ("\n" );
                   2919: /*
                   2920:   Determine the range of the rows in this strip.
                   2921: */
                   2922:     if ( 1 < ilo ){
                   2923:       i2lo = ilo;
                   2924:     }else{
                   2925:       i2lo = 1;
                   2926:     }
                   2927:     if ( m < ihi ){
                   2928:       i2hi = m;
                   2929:     }else{
                   2930:       i2hi = ihi;
                   2931:     }
                   2932: 
                   2933:     for ( i = i2lo; i <= i2hi; i++ ){
                   2934: /*
                   2935:   Print out (up to) 5 entries in row I, that lie in the current strip.
                   2936: */
                   2937:       /* fprintf ( ficlog, "%5d:", i - 1 ); */
                   2938:       /* printf ("%5d:", i - 1 ); */
                   2939:       printf ("%5d:", i );
                   2940:       for ( j = j2lo; j <= j2hi; j++ )
                   2941:       {
                   2942:         /* fprintf ( ficlog, "  %14g", a[i-1+(j-1)*m] ); */
                   2943:         /* printf ("%14.7g  ", a[i-1+(j-1)*m] ); */
                   2944:            /* printf("%14.7f  ", v[i-1][j-1]); */
                   2945:            printf("%14.7f  ", v[i][j]);
                   2946:         /* fprintf ( stdout, "  %14g", a[i-1+(j-1)*m] ); */
                   2947:       }
                   2948:       /* fprintf ( ficlog, "\n" ); */
                   2949:       printf ("\n" );
                   2950:     }
                   2951:   }
                   2952:  
                   2953:    /* printf("%s\n", s); */
                   2954:    /* for (k=0; k<n; k++) { */
                   2955:    /*     for (i=0; i<n; i++) { */
                   2956:    /*         /\* printf("%20.10e ", v[k][i]); *\/ */
                   2957:    /*     } */
                   2958:    /*     printf("\n"); */
                   2959:    /* } */
                   2960: #undef INCX  
                   2961: }
                   2962: 
                   2963: void vecprint(char *s, double *x, int n)
                   2964: /* char *s; */
                   2965: /* double x[N]; */
                   2966: {
                   2967:    int i=0;
                   2968:    
                   2969:    printf(" %s", s);
                   2970:    /* for (i=0; i<n; i++) */
                   2971:    for (i=1; i<=n; i++)
                   2972:      printf ("  %14.7g",  x[i] );
                   2973:      /* printf("  %8d: %14g\n", i, x[i]); */
                   2974:    printf ("\n" ); 
                   2975: }
                   2976: 
                   2977: static void print()            /* print a line of traces */
                   2978: {
                   2979:  
                   2980: 
                   2981:    printf("\n");
                   2982:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   2983:    /* printf("... after %u function calls ...\n", nf); */
                   2984:    /* printf("... including %u linear searches ...\n", nl); */
                   2985:    printf("%10d    %10d%14.7g",nl, nf, fx);
                   2986:    vecprint("... current values of x ...", x, n);
                   2987: }
                   2988: /* static void print2(int n, double *x, int prin, double fx, int nf, int nl) */ /* print a line of traces */
                   2989: static void print2() /* print a line of traces */
                   2990: {
                   2991:   int i; double fmin=0.;
                   2992: 
                   2993:    /* printf("\n"); */
                   2994:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   2995:    /* printf("... after %u function calls ...\n", nf); */
                   2996:    /* printf("... including %u linear searches ...\n", nl); */
                   2997:    /* printf("%10d    %10d%14.7g",nl, nf, fx); */
                   2998:   printf ( "\n" );
                   2999:   printf ( "  Linear searches      %d", nl );
                   3000:   /* printf ( "  Linear searches      %d\n", nl ); */
                   3001:   /* printf ( "  Function evaluations %d\n", nf ); */
                   3002:   /* printf ( "  Function value FX = %g\n", fx ); */
                   3003:   printf ( "  Function evaluations %d", nf );
                   3004:   printf ( "  Function value FX = %.12lf\n", fx );
                   3005: #ifdef DEBUGPRAX
                   3006:    printf("n=%d prin=%d\n",n,prin);
                   3007: #endif
                   3008:    if(fx <= fmin) printf(" UNDEFINED "); else  printf("%14.7g",log(fx-fmin));
                   3009:    if ( n <= 4 || 2 < prin )
                   3010:    {
                   3011:      /* for(i=1;i<=n;i++)printf("%14.7g",x[i-1]); */
                   3012:      for(i=1;i<=n;i++)printf("%14.7g",x[i]);
                   3013:      /* r8vec_print ( n, x, "  X:" ); */
                   3014:    }
                   3015:    printf("\n");
                   3016:  }
                   3017: 
                   3018: 
                   3019: /* #ifdef MSDOS */
                   3020: /* static double tflin[N]; */
                   3021: /* #endif */
                   3022: 
                   3023: static double flin(double l, int j)
                   3024: /* double l; */
                   3025: {
                   3026:    int i;
                   3027:    /* #ifndef MSDOS */
                   3028:    /*    double tflin[N]; */
                   3029:    /* #endif    */
                   3030:    /* double *tflin; */ /* Be careful to put tflin on a vector n */
                   3031: 
                   3032:    /* j is used from 0 to n-1 and can be -1 for parabolic search */
                   3033: 
                   3034:    /* if (j != -1) {           /\* linear search *\/ */
                   3035:    if (j > 0) {                /* linear search */
                   3036:      /* for (i=0; i<n; i++){ */
                   3037:      for (i=1; i<=n; i++){
                   3038:           tflin[i] = x[i] + l *v[i][j];
                   3039: #ifdef DEBUGPRAX
                   3040:          /* printf("     flin i=%14d t=%14.7f x=%14.7f l=%14.7f v[%d,%d]=%14.7f nf=%14d\n",i+1, tflin[i],x[i],l,i,j,v[i][j],nf); */
                   3041:          printf("     flin i=%14d t=%14.7f x=%14.7f l=%14.7f v[%d,%d]=%14.7f nf=%14d\n",i, tflin[i],x[i],l,i,j,v[i][j],nf);
                   3042: #endif
                   3043:      }
                   3044:    }
                   3045:    else {                      /* search along parabolic space curve */
                   3046:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3047:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3048:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3049: #ifdef DEBUGPRAX      
                   3050:       printf("     search along a parabolic space curve. j=%14d nf=%14d l=%14.7f qd0=%14.7f qd1=%14.7f\n",j,nf,l,qd0,qd1);
                   3051: #endif
                   3052:       /* for (i=0; i<n; i++){ */
                   3053:       for (i=1; i<=n; i++){
                   3054:           tflin[i] = qa*q0[i]+qb*x[i]+qc*q1[i];
                   3055: #ifdef DEBUGPRAX
                   3056:           /* printf("      parabole i=%14d t(i)=%14.7f q0=%14.7f x=%14.7f q1=%14.7f\n",i+1,tflin[i],q0[i],x[i],q1[i]); */
                   3057:           printf("      parabole i=%14d t(i)=%14.7e q0=%14.7e x=%14.7e q1=%14.7e\n",i,tflin[i],q0[i],x[i],q1[i]);
                   3058: #endif
                   3059:       }
                   3060:    }
                   3061:    nf++;
                   3062: 
                   3063: #ifdef NR_SHIFT
                   3064:       return (*fun)((tflin-1), n);
                   3065: #else
                   3066:      /* return (*fun)(tflin, n);*/
                   3067:       return (*fun)(tflin);
                   3068: #endif
                   3069: }
                   3070: 
                   3071: void minny(int j, int nits, double *d2, double *x1, double f1, int fk)
                   3072: /* double *d2, *x1, f1; */
                   3073: {
                   3074: /* here j is from 0 to n-1 and can be -1 for parabolic search  */
                   3075:   /*      MINIMIZES F FROM X IN THE DIRECTION V(*,J) */
                   3076:           /*      UNLESS J<1, WHEN A QUADRATIC SEARCH IS DONE */
                   3077:           /*      IN THE PLANE DEFINED BY Q0, Q1 AND X. */
                   3078:           /*      D2 AN APPROXIMATION TO HALF F'' (OR ZERO), */
                   3079:           /*      X1 AN ESTIMATE OF DISTANCE TO MINIMUM, */
                   3080:           /*      RETURNED AS THE DISTANCE FOUND. */
                   3081:           /*       IF FK = TRUE THEN F1 IS FLIN(X1), OTHERWISE */
                   3082:           /*       X1 AND F1 ARE IGNORED ON ENTRY UNLESS FINAL */
                   3083:           /*       FX > F1. NITS CONTROLS THE NUMBER OF TIMES */
                   3084:           /*       AN ATTEMPT IS MADE TO HALVE THE INTERVAL. */
                   3085:           /* SIDE EFFECTS: USES AND ALTERS X, FX, NF, NL. */
                   3086:           /*       IF J < 1 USES VARIABLES Q... . */
                   3087:          /*       USES H, N, T, M2, M4, LDT, DMIN, MACHEPS; */
                   3088:    int k, i, dz;
                   3089:    double x2, xm, f0, f2, fm, d1, t2, sf1, sx1;
                   3090:    double s;
                   3091:    double macheps;
                   3092:    macheps=pow(16.0,-13.0);
                   3093:    sf1 = f1; sx1 = *x1;
                   3094:    k = 0; xm = 0.0; fm = f0 = fx; dz = *d2 < macheps;
                   3095:    /* h=1.0;*/ /* To be revised */
                   3096: #ifdef DEBUGPRAX
                   3097:    /* printf("min macheps=%14g h=%14g step=%14g t=%14g fx=%14g\n",macheps,h, step,t, fx);  */
                   3098:    /* Where is fx coming from */
                   3099:    printf("   min macheps=%14g h=%14g  t=%14g fx=%.9lf dirj=%d\n",macheps, h, t, fx, j);
                   3100:    matprint("  min vectors:",v,n,n);
                   3101: #endif
                   3102:    /* find step size */
                   3103:    s = 0.;
                   3104:    /* for (i=0; i<n; i++) s += x[i]*x[i]; */
                   3105:    for (i=1; i<=n; i++) s += x[i]*x[i];
                   3106:    s = sqrt(s);
                   3107:    if (dz)
                   3108:       t2 = m4*sqrt(fabs(fx)/dmin + s*ldt) + m2*ldt;
                   3109:    else
                   3110:       t2 = m4*sqrt(fabs(fx)/(*d2) + s*ldt) + m2*ldt;
                   3111:    s = s*m4 + t;
                   3112:    if (dz && t2 > s) t2 = s;
                   3113:    if (t2 < small_windows) t2 = small_windows;
                   3114:    if (t2 > 0.01*h) t2 = 0.01 * h;
                   3115:    if (fk && f1 <= fm) {
                   3116:       xm = *x1;
                   3117:       fm = f1;
                   3118:    }
                   3119: #ifdef DEBUGPRAX
                   3120:    printf("   additional flin X1=%14.7f t2=%14.7f *f1=%14.7f fm=%14.7f fk=%d\n",*x1,t2,f1,fm,fk);
                   3121: #endif   
                   3122:    if (!fk || fabs(*x1) < t2) {
                   3123:      *x1 = (*x1 >= 0 ? t2 : -t2); 
                   3124:       /* *x1 = (*x1 > 0 ? t2 : -t2); */ /* kind of error */
                   3125: #ifdef DEBUGPRAX
                   3126:      printf("    additional flin X1=%16.10e dirj=%d fk=%d\n",*x1, j, fk);
                   3127: #endif
                   3128:       f1 = flin(*x1, j);
                   3129: #ifdef DEBUGPRAX
                   3130:     printf("    after flin f1=%18.12e dirj=%d fk=%d\n",f1, j,fk);
                   3131: #endif
                   3132:    }
                   3133:    if (f1 <= fm) {
                   3134:       xm = *x1;
                   3135:       fm = f1;
                   3136:    }
                   3137: L0: /*L0 loop or next */
                   3138: /*
                   3139:   Evaluate FLIN at another point and estimate the second derivative.
                   3140: */
                   3141:    if (dz) {
                   3142:       x2 = (f0 < f1 ? -(*x1) : 2*(*x1));
                   3143: #ifdef DEBUGPRAX
                   3144:       printf("     additional second flin x2=%14.8e x1=%14.8e f0=%14.8e f1=%18.12e dirj=%d\n",x2,*x1,f0,f1,j);
                   3145: #endif
                   3146:       f2 = flin(x2, j);
                   3147: #ifdef DEBUGPRAX
                   3148:       printf("     additional second flin x2=%16.10e x1=%16.10e f1=%18.12e f0=%18.10e f2=%18.10e fm=%18.10e\n",x2, *x1, f1,f0,f2,fm);
                   3149: #endif
                   3150:       if (f2 <= fm) {
                   3151:          xm = x2;
                   3152:         fm = f2;
                   3153:       }
                   3154:       /* d2 is the curvature or double difference f1 doesn't seem to be accurately computed */
                   3155:       *d2 = (x2*(f1-f0) - (*x1)*(f2-f0))/((*x1)*x2*((*x1)-x2));
                   3156: #ifdef DEBUGPRAX
                   3157:       double d11,d12;
                   3158:       d11=(f1-f0)/(*x1);d12=(f2-f0)/x2;
                   3159:       printf(" d11=%18.12e d12=%18.12e d11-d12=%18.12e x1-x2=%18.12e (d11-d12)/(x2-(*x1))=%18.12e\n", d11 ,d12, d11-d12, x2-(*x1), (d11-d12)/(x2-(*x1)));
                   3160:       printf(" original computing f1=%18.12e *d2=%16.10e f0=%18.12e f1-f0=%16.10e f2-f0=%16.10e\n",f1,*d2,f0,f1-f0, f2-f0);
                   3161:       double ff1=7.783920622852e+04;
                   3162:       double f1mf0=9.0344736236e-05;
                   3163:       *d2 = (f1mf0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2);
                   3164:       /* *d2 = (ff1-f0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2); */
                   3165:       printf(" simpliff computing *d2=%16.10e f1mf0=%18.12e,f1=f0+f1mf0=%18.12e\n",*d2,f1mf0,f0+f1mf0);
                   3166:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);
                   3167:       printf(" overlifi computing *d2=%16.10e\n",*d2);
                   3168: #endif
                   3169:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);      
                   3170:    }
                   3171: #ifdef DEBUGPRAX
                   3172:       printf("    additional second flin xm=%14.8e fm=%14.8e *d2=%14.8e\n",xm, fm,*d2);
                   3173: #endif
                   3174:    /*
                   3175:      Estimate the first derivative at 0.
                   3176:    */
                   3177:    d1 = (f1-f0)/(*x1) - *x1**d2; dz = 1;
                   3178:    /*
                   3179:       Predict the minimum.
                   3180:     */
                   3181:    if (*d2 <= small_windows) {
                   3182:      x2 = (d1 < 0 ? h : -h);
                   3183:    }
                   3184:    else {
                   3185:       x2 = - 0.5*d1/(*d2);
                   3186:    }
                   3187: #ifdef DEBUGPRAX
                   3188:     printf("   AT d1=%14.8e d2=%14.8e small=%14.8e dz=%d x1=%14.8e x2=%14.8e\n",d1,*d2,small_windows,dz,*x1,x2);
                   3189: #endif
                   3190:     if (fabs(x2) > h)
                   3191:       x2 = (x2 > 0 ? h : -h);
                   3192: L1:  /* L1 or try loop */
                   3193: #ifdef DEBUGPRAX
                   3194:     printf("   AT predicted minimum flin x2=%14.8e x1=%14.8e K=%14d NITS=%14d dirj=%d\n",x2,*x1,k,nits,j);
                   3195: #endif
                   3196:    f2 = flin(x2, j); /* x[i]+x2*v[i][j] */
                   3197: #ifdef DEBUGPRAX
                   3198:    printf("   after flin f0=%14.8e f1=%14.8e f2=%14.8e fm=%14.8e\n",f0,f1,f2, fm);
                   3199: #endif
                   3200:    if ((k < nits) && (f2 > f0)) {
                   3201: #ifdef DEBUGPRAX
                   3202:      printf("  NO SUCCESS SO TRY AGAIN;\n");
                   3203: #endif
                   3204:      k++;
                   3205:      if ((f0 < f1) && (*x1*x2 > 0.0))
                   3206:        goto L0; /* or next */
                   3207:      x2 *= 0.5;
                   3208:      goto L1;
                   3209:    }
                   3210:    nl++;
                   3211: #ifdef DEBUGPRAX
                   3212:    printf(" bebeBE end of min x1=%14.8e x2=%14.8e f1=%14.8e f2=%14.8e f0=%14.8e fm=%14.8e d2=%14.8e\n",*x1, x2, f1, f2, f0, fm, *d2);
                   3213: #endif
                   3214:    if (f2 > fm) x2 = xm; else fm = f2;
                   3215:    if (fabs(x2*(x2-*x1)) > small_windows) {
                   3216:       *d2 = (x2*(f1-f0) - *x1*(fm-f0))/(*x1*x2*(*x1-x2));
                   3217:    }
                   3218:    else {
                   3219:       if (k > 0) *d2 = 0;
                   3220:    }
                   3221: #ifdef DEBUGPRAX
                   3222:    printf(" bebe end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3223: #endif
                   3224:    if (*d2 <= small_windows) *d2 = small_windows;
                   3225:    *x1 = x2; fx = fm;
                   3226:    if (sf1 < fx) {
                   3227:       fx = sf1;
                   3228:       *x1 = sx1;
                   3229:    }
                   3230:   /*
                   3231:     Update X for linear search.
                   3232:   */
                   3233: #ifdef DEBUGPRAX
                   3234:    printf("  end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3235: #endif
                   3236:    
                   3237:    /* if (j != -1) */
                   3238:    /*    for (i=0; i<n; i++) */
                   3239:    /*        x[i] += (*x1)*v[i][j]; */
                   3240:    if (j > 0)
                   3241:       for (i=1; i<=n; i++)
                   3242:           x[i] += (*x1)*v[i][j];
                   3243: }
                   3244: 
                   3245: void quad()    /* look for a minimum along the curve q0, q1, q2        */
                   3246: {
                   3247:    int i;
                   3248:    double l, s;
                   3249: 
                   3250:    s = fx; fx = qf1; qf1 = s; qd1 = 0.0;
                   3251:    /* for (i=0; i<n; i++) { */
                   3252:    for (i=1; i<=n; i++) {
                   3253:        s = x[i]; l = q1[i]; x[i] = l; q1[i] = s;
                   3254:        qd1 = qd1 + (s-l)*(s-l);
                   3255:    }
                   3256:    s = 0.0; qd1 = sqrt(qd1); l = qd1;
                   3257: #ifdef DEBUGPRAX
                   3258:   printf("  QUAD after sqrt qd1=%14.8e \n",qd1);
                   3259: #endif
                   3260:  
                   3261:    if (qd0>0.0 && qd1>0.0 &&nl>=3*n*n) {
                   3262: #ifdef DEBUGPRAX
                   3263:      printf(" QUAD before min value=%14.8e \n",qf1);
                   3264: #endif
                   3265:       /* min(-1, 2, &s, &l, qf1, 1); */
                   3266:       minny(0, 2, &s, &l, qf1, 1);
                   3267:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3268:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3269:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3270:    }
                   3271:    else {
                   3272:       fx = qf1; qa = qb = 0.0; qc = 1.0;
                   3273:    }
                   3274: #ifdef DEBUGPRAX
                   3275:   printf("after eventual min qd0=%14.8e qd1=%14.8e nl=%d\n",qd0, qd1,nl);
                   3276: #endif
                   3277:    qd0 = qd1;
                   3278:    /* for (i=0; i<n; i++) { */
                   3279:    for (i=1; i<=n; i++) {
                   3280:        s = q0[i]; q0[i] = x[i];
                   3281:        x[i] = qa*s + qb*x[i] + qc*q1[i];
                   3282:    }
                   3283: #ifdef DEBUGQUAD
                   3284:    vecprint ( " X after QUAD:" , x, n );
                   3285: #endif
                   3286: }
                   3287: 
                   3288: /* void minfit(int n, double eps, double tol, double ab[N][N], double q[]) */
                   3289: void minfit(int n, double eps, double tol, double **ab, double q[])
                   3290: /* int n; */
                   3291: /* double eps, tol, ab[N][N], q[N]; */
                   3292: {
                   3293:    int l, kt, l2, i, j, k;
                   3294:    double c, f, g, h, s, x, y, z;
                   3295:    /* double eps; */
                   3296: /* #ifndef MSDOS */
                   3297: /*    double e[N];             /\* plenty of stack on a vax *\/ */
                   3298: /* #endif */
                   3299:    /* double *e; */
                   3300:    /* e=vector(0,n-1); /\* should be freed somewhere but gotos *\/ */
                   3301:    
                   3302:    /* householder's reduction to bidiagonal form */
                   3303: 
                   3304:    if(n==1){
                   3305:      /* q[1-1]=ab[1-1][1-1]; */
                   3306:      /* ab[1-1][1-1]=1.0; */
                   3307:      q[1]=ab[1][1];
                   3308:      ab[1][1]=1.0;
                   3309:      return; /* added from hardt */
                   3310:    }
                   3311:    /* eps=macheps; */ /* added */
                   3312:    x = g = 0.0;
                   3313: #ifdef DEBUGPRAX
                   3314:    matprint (" HOUSE holder:", ab, n, n);
                   3315: #endif
                   3316: 
                   3317:    /* for (i=0; i<n; i++) {  /\* FOR I := 1 UNTIL N DO *\/ */
                   3318:    for (i=1; i<=n; i++) {  /* FOR I := 1 UNTIL N DO */
                   3319:      e[i] = g; s = 0.0; l = i+1;
                   3320:      /* for (j=i; j<n; j++)  /\* FOR J := I UNTIL N DO S := S*AB(J,I)**2; *\/ /\* not correct *\/ */
                   3321:      for (j=i; j<=n; j++)  /* FOR J := I UNTIL N DO S := S*AB(J,I)**2; */ /* not correct */
                   3322:        s += ab[j][i] * ab[j][i];
                   3323: #ifdef DEBUGPRAXFIN
                   3324:      printf("i=%d s=%d %.7g tol=%.7g",i,s,tol);
                   3325: #endif
                   3326:      if (s < tol) {
                   3327:        g = 0.0;
                   3328:      }
                   3329:      else {
                   3330:        /* f = ab[i][i]; */
                   3331:        f = ab[i][i];
                   3332:        if (f < 0.0) 
                   3333:         g = sqrt(s);
                   3334:        else
                   3335:         g = -sqrt(s);
                   3336:        /* h = f*g - s; ab[i][i] = f - g; */
                   3337:        h = f*g - s; ab[i][i] = f - g;
                   3338:        /* for (j=l; j<n; j++) { */ /* FOR J := L UNTIL N DO */ /* wrong */
                   3339:        for (j=l; j<=n; j++) {
                   3340:         f = 0.0;
                   3341:         /* for (k=i; k<n; k++) /\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3342:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3343:           /* f += ab[k][i] * ab[k][j]; */
                   3344:           f += ab[k][i] * ab[k][j];
                   3345:         f /= h;
                   3346:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3347:           /* for (k=i; k<n; k++)/\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3348:           ab[k][j] += f * ab[k][i];
                   3349:         /* ab[k][j] += f * ab[k][i]; */
                   3350: #ifdef DEBUGPRAX
                   3351:         printf("Holder J=%d F=%.7g",j,f);
                   3352: #endif
                   3353:        }
                   3354:      } /* end s */
                   3355:      /* q[i] = g; s = 0.0; */
                   3356:      q[i] = g; s = 0.0;
                   3357: #ifdef DEBUGPRAX
                   3358:      printf(" I Q=%d %.7g",i,q[i]);
                   3359: #endif   
                   3360:        
                   3361:      /* if (i < n) */
                   3362:      /* if (i <= n)  /\* I is always lower or equal to n wasn't in golub reinsch*\/ */
                   3363:      /* for (j=l; j<n; j++) */
                   3364:      for (j=l; j<=n; j++)
                   3365:        s += ab[i][j] * ab[i][j];
                   3366:      /* s += ab[i][j] * ab[i][j]; */
                   3367:      if (s < tol) {
                   3368:        g = 0.0;
                   3369:      }
                   3370:      else {
                   3371:        if(i<n)
                   3372:         /* f = ab[i][i+1]; */ /* Brent golub overflow */
                   3373:         f = ab[i][i+1];
                   3374:        if (f < 0.0)
                   3375:         g = sqrt(s);
                   3376:        else 
                   3377:         g = - sqrt(s);
                   3378:        h = f*g - s;
                   3379:        /* h = f*g - s; ab[i][i+1] = f - g; */ /* Overflow for i=n Error in Golub too but not Burkardt*/
                   3380:        /* for (j=l; j<n; j++) */
                   3381:        /*     e[j] = ab[i][j]/h; */
                   3382:        if(i<n){
                   3383:         ab[i][i+1] = f - g;
                   3384:         for (j=l; j<=n; j++)
                   3385:           e[j] = ab[i][j]/h;
                   3386:         /* for (j=l; j<n; j++) { */
                   3387:         for (j=l; j<=n; j++) {
                   3388:           s = 0.0;
                   3389:           /* for (k=l; k<n; k++) s += ab[j][k]*ab[i][k]; */
                   3390:           for (k=l; k<=n; k++) s += ab[j][k]*ab[i][k];
                   3391:           /* for (k=l; k<n; k++) ab[j][k] += s * e[k]; */
                   3392:           for (k=l; k<=n; k++) ab[j][k] += s * e[k];
                   3393:         } /* END J */
                   3394:        } /* END i <n */
                   3395:      } /* end s */
                   3396:        /* y = fabs(q[i]) + fabs(e[i]); */
                   3397:      y = fabs(q[i]) + fabs(e[i]);
                   3398:      if (y > x) x = y;
                   3399: #ifdef DEBUGPRAX
                   3400:      printf(" I Y=%d %.7g",i,y);
                   3401: #endif
                   3402: #ifdef DEBUGPRAX
                   3403:      printf(" i=%d e(i) %.7g",i,e[i]);
                   3404: #endif
                   3405:    } /* end i */
                   3406:    /*
                   3407:      Accumulation of right hand transformations */
                   3408:    /* for (i=n-1; i >= 0; i--) { */ /* FOR I := N STEP -1 UNTIL 1 DO */
                   3409:    /* We should avoid the overflow in Golub */
                   3410:    /* ab[n-1][n-1] = 1.0; */
                   3411:    /* g = e[n-1]; */
                   3412:    ab[n][n] = 1.0;
                   3413:    g = e[n];
                   3414:    l = n;
                   3415: 
                   3416:    /* for (i=n; i >= 1; i--) { */
                   3417:    for (i=n-1; i >= 1; i--) { /* n-1 loops, different from brent and golub*/
                   3418:      if (g != 0.0) {
                   3419:        /* h = ab[i-1][i]*g; */
                   3420:        h = ab[i][i+1]*g;
                   3421:        for (j=l; j<=n; j++) ab[j][i] = ab[i][j] / h;
                   3422:        for (j=l; j<=n; j++) {
                   3423:         /* h = ab[i][i+1]*g; */
                   3424:         /* for (j=l; j<n; j++) ab[j][i] = ab[i][j] / h; */
                   3425:         /* for (j=l; j<n; j++) { */
                   3426:         s = 0.0;
                   3427:         /* for (k=l; k<n; k++) s += ab[i][k] * ab[k][j]; */
                   3428:         /* for (k=l; k<n; k++) ab[k][j] += s * ab[k][i]; */
                   3429:         for (k=l; k<=n; k++) s += ab[i][k] * ab[k][j];
                   3430:         for (k=l; k<=n; k++) ab[k][j] += s * ab[k][i];
                   3431:        }/* END J */
                   3432:      }/* END G */
                   3433:      /* for (j=l; j<n; j++) */
                   3434:      /*     ab[i][j] = ab[j][i] = 0.0; */
                   3435:      /* ab[i][i] = 1.0; g = e[i]; l = i; */
                   3436:      for (j=l; j<=n; j++)
                   3437:        ab[i][j] = ab[j][i] = 0.0;
                   3438:      ab[i][i] = 1.0; g = e[i]; l = i;
                   3439:    }/* END I */
                   3440: #ifdef DEBUGPRAX
                   3441:    matprint (" HOUSE accumulation:",ab,n, n );
                   3442: #endif
                   3443: 
                   3444:    /* diagonalization to bidiagonal form */
                   3445:    eps *= x;
                   3446:    /* for (k=n-1; k>= 0; k--) { */
                   3447:    for (k=n; k>= 1; k--) {
                   3448:      kt = 0;
                   3449: TestFsplitting:
                   3450: #ifdef DEBUGPRAX
                   3451:      printf(" TestFsplitting: k=%d kt=%d\n",k,kt);
                   3452:      /* for(i=1;i<=n;i++)printf(" e(%d)=%.14f",i,e[i]);printf("\n"); */
                   3453: #endif     
                   3454:      kt = kt+1; 
                   3455: /* TestFsplitting: */
                   3456:      /* if (++kt > 30) { */
                   3457:      if (kt > 30) { 
                   3458:        e[k] = 0.0;
                   3459:        fprintf(stderr, "\n+++ MINFIT - Fatal error\n");
                   3460:        fprintf ( stderr, "  The QR algorithm failed to converge.\n" );
                   3461:      }
                   3462:      /* for (l2=k; l2>=0; l2--) { */
                   3463:      for (l2=k; l2>=1; l2--) {
                   3464:        l = l2;
                   3465: #ifdef DEBUGPRAX
                   3466:        printf(" l e(l)< eps %d %.7g %.7g ",l,e[l], eps);
                   3467: #endif
                   3468:        /* if (fabs(e[l]) <= eps) */
                   3469:        if (fabs(e[l]) <= eps)
                   3470:         goto TestFconvergence;
                   3471:        /* if (fabs(q[l-1]) <= eps)*/ /* missing if ( 1 < l ){ *//* printf(" q(l-1)< eps %d %.7g %.7g ",l-1,q[l-2], eps); */
                   3472:        if (fabs(q[l-1]) <= eps)
                   3473:         break; /* goto Cancellation; */
                   3474:      }
                   3475:    Cancellation:
                   3476: #ifdef DEBUGPRAX
                   3477:      printf(" Cancellation:\n");
                   3478: #endif     
                   3479:      c = 0.0; s = 1.0;
                   3480:      for (i=l; i<=k; i++) {
                   3481:        f = s * e[i]; e[i] *= c;
                   3482:        /* f = s * e[i]; e[i] *= c; */
                   3483:        if (fabs(f) <= eps)
                   3484:         goto TestFconvergence;
                   3485:        /* g = q[i]; */
                   3486:        g = q[i];
                   3487:        if (fabs(f) < fabs(g)) {
                   3488:         double fg = f/g;
                   3489:         h = fabs(g)*sqrt(1.0+fg*fg);
                   3490:        }
                   3491:        else {
                   3492:         double gf = g/f;
                   3493:         h = (f!=0.0 ? fabs(f)*sqrt(1.0+gf*gf) : 0.0);
                   3494:        }
                   3495:        /*    COMMENT: THE ABOVE REPLACES Q(I):=H:=LONGSQRT(G*G+F*F) */
                   3496:        /* WHICH MAY GIVE INCORRECT RESULTS IF THE */
                   3497:        /* SQUARES UNDERFLOW OR IF F = G = 0; */
                   3498:        
                   3499:        /* q[i] = h; */
                   3500:        q[i] = h;
                   3501:        if (h == 0.0) { h = 1.0; g = 1.0; }
                   3502:        c = g/h; s = -f/h;
                   3503:      }
                   3504: TestFconvergence:
                   3505:  #ifdef DEBUGPRAX
                   3506:      printf(" TestFconvergence: l=%d k=%d\n",l,k);
                   3507: #endif     
                   3508:      /* z = q[k]; */
                   3509:      z = q[k];
                   3510:      if (l == k)
                   3511:        goto Convergence;
                   3512:      /* shift from bottom 2x2 minor */
                   3513:      /* x = q[l]; y = q[k-l]; g = e[k-1]; h = e[k]; */ /* Error */
                   3514:      x = q[l]; y = q[k-1]; g = e[k-1]; h = e[k];
                   3515:      f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2.0*h*y);
                   3516:      g = sqrt(f*f+1.0);
                   3517:      if (f <= 0.0)
                   3518:        f = ((x-z)*(x+z) + h*(y/(f-g)-h))/x;
                   3519:      else
                   3520:        f = ((x-z)*(x+z) + h*(y/(f+g)-h))/x;
                   3521:      /* next qr transformation */
                   3522:      s = c = 1.0;
                   3523:      for (i=l+1; i<=k; i++) {
                   3524: #ifdef DEBUGPRAXQR
                   3525:        printf(" Before Mid TestFconvergence: l+1=%d i=%d k=%d h=%.6e e(i)=%14.8f e(i-1)=%14.8f\n",l+1,i,k, h, e[i],e[i-1]);
                   3526: #endif     
                   3527:        /* g = e[i]; y = q[i]; h = s*g; g *= c; */
                   3528:        g = e[i]; y = q[i]; h = s*g; g *= c;
                   3529:        if (fabs(f) < fabs(h)) {
                   3530:         double fh = f/h;
                   3531:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3532:        }
                   3533:        else {
                   3534:         double hf = h/f;
                   3535:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3536:        }
                   3537:        /* e[i-1] = z; */
                   3538:        e[i-1] = z;
                   3539: #ifdef DEBUGPRAXQR
                   3540:        printf(" Mid TestFconvergence: l+1=%d i=%d k=%d h=%.6e e(i)=%14.8f e(i-1)=%14.8f\n",l+1,i,k, h, e[i],e[i-1]);
                   3541: #endif     
                   3542:        if (z == 0.0) 
                   3543:         f = z = 1.0;
                   3544:        c = f/z; s = h/z;
                   3545:        f = x*c + g*s; g = - x*s + g*c; h = y*s;
                   3546:        y *= c;
                   3547:        /* for (j=0; j<n; j++) { */
                   3548:        /*     x = ab[j][i-1]; z = ab[j][i]; */
                   3549:        /*     ab[j][i-1] = x*c + z*s; */
                   3550:        /*     ab[j][i] = - x*s + z*c; */
                   3551:        /* } */
                   3552:        for (j=1; j<=n; j++) {
                   3553:         x = ab[j][i-1]; z = ab[j][i];
                   3554:         ab[j][i-1] = x*c + z*s;
                   3555:         ab[j][i] = - x*s + z*c;
                   3556:        }
                   3557:        if (fabs(f) < fabs(h)) {
                   3558:         double fh = f/h;
                   3559:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3560:        }
                   3561:        else {
                   3562:         double hf = h/f;
                   3563:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3564:        }
                   3565: #ifdef DEBUGPRAXQR
                   3566:        printf(" qr transformation z f h=%.7g %.7g %.7g i=%d k=%d\n",z,f,h, i, k);
                   3567: #endif
                   3568:        q[i-1] = z;
                   3569:        if (z == 0.0)
                   3570:         z = f = 1.0;
                   3571:        c = f/z; s = h/z;
                   3572:        f = c*g + s*y;  /* f can be very small */
                   3573:        x = - s*g + c*y;
                   3574:      }
                   3575:      /* e[l] = 0.0; e[k] = f; q[k] = x; */
                   3576:      e[l] = 0.0; e[k] = f; q[k] = x;
                   3577: #ifdef DEBUGPRAXQR
                   3578:      printf(" aftermid loop l=%d k=%d e(l)=%7g e(k)=%.7g q(k)=%.7g x=%.7g\n",l,k,e[l],e[k],q[k],x);
                   3579: #endif
                   3580:      goto TestFsplitting;
                   3581:    Convergence:
                   3582: #ifdef DEBUGPRAX
                   3583:      printf(" Convergence:\n");
                   3584: #endif     
                   3585:      if (z < 0.0) {
                   3586:        /* q[k] = - z; */
                   3587:        /* for (j=0; j<n; j++) ab[j][k] = - ab[j][k]; */
                   3588:        q[k] = - z;
                   3589:        for (j=1; j<=n; j++) ab[j][k] = - ab[j][k];
                   3590:      }/* END Z */
                   3591:    }/* END K */
                   3592: } /* END MINFIT */
                   3593: 
                   3594: 
                   3595: double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x))
                   3596: /* double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x, int _n)) */
                   3597: /* double praxis(double (*_fun)(), double _x[], int _n) */
                   3598: /* double (*_fun)(); */
                   3599: /* double _x[N]; */
                   3600: /* double (*_fun)(); */
                   3601: /* double _x[N]; */
                   3602: {
                   3603:    /* init global extern variables and parameters */
                   3604:    /* double *d, *y, *z, */
                   3605:    /*   *q0, *q1, **v; */
                   3606:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   3607:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   3608: 
                   3609:   
                   3610:   int seed; /* added */
                   3611:   int biter=0;
                   3612:   double r;
                   3613:   double randbrent( int (*));
                   3614:   double s, sf;
                   3615:   
                   3616:    h = h0; /* step; */
                   3617:    t = tol;
                   3618:    scbd = 1.0;
                   3619:    illc = 0;
                   3620:    ktm = 1;
                   3621: 
                   3622:    macheps = DBL_EPSILON;
                   3623:    /* prin=4; */
                   3624: #ifdef DEBUGPRAX
                   3625:    printf("Praxis macheps=%14g h=%14g step=%14g tol=%14g\n",macheps,h, h0,tol); 
                   3626: #endif
                   3627:    n = _n;
                   3628:    x = _x;
                   3629:    prin = _prin;
                   3630:    fun = _fun;
                   3631:    d=vector(1, n);
                   3632:    y=vector(1, n);
                   3633:    z=vector(1, n);
                   3634:    q0=vector(1, n);
                   3635:    q1=vector(1, n);
                   3636:    e=vector(1, n);
                   3637:    tflin=vector(1, n);
                   3638:    v=matrix(1, n, 1, n);
                   3639:    for(i=1;i<=n;i++){d[i]=y[i]=z[i]=q0[0]=e[i]=tflin[i]=0.;}
                   3640:    small_windows = (macheps) * (macheps); vsmall = small_windows*small_windows;
                   3641:    large = 1.0/small_windows; vlarge = 1.0/vsmall;
                   3642:    m2 = sqrt(macheps); m4 = sqrt(m2);
                   3643:    seed = 123456789; /* added */
                   3644:    ldfac = (illc ? 0.1 : 0.01);
                   3645:    for(i=1;i<=n;i++) z[i]=0.; /* Was missing in Gegenfurtner as well as Brent's algol or fortran  */
                   3646:    nl = kt = 0; nf = 1;
                   3647: #ifdef NR_SHIFT
                   3648:    fx = (*fun)((x-1), n);
                   3649: #else
                   3650:    fx = (*fun)(x);
                   3651: #endif
                   3652:    qf1 = fx;
                   3653:    t2 = small_windows + fabs(t); t = t2; dmin = small_windows;
                   3654: #ifdef DEBUGPRAX
                   3655:    printf("praxis2 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3656: #endif
                   3657:    if (h < 100.0*t) h = 100.0*t;
                   3658: #ifdef DEBUGPRAX
                   3659:    printf("praxis3 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3660: #endif
                   3661:    ldt = h;
                   3662:    /* for (i=0; i<n; i++) for (j=0; j<n; j++) */
                   3663:    for (i=1; i<=n; i++) for (j=1; j<=n; j++)
                   3664:        v[i][j] = (i == j ? 1.0 : 0.0);
                   3665:    d[1] = 0.0; qd0 = 0.0;
                   3666:    /* for (i=0; i<n; i++) q1[i] = x[i]; */
                   3667:    for (i=1; i<=n; i++) q1[i] = x[i];
                   3668:    if (prin > 1) {
                   3669:       printf("\n------------- enter function praxis -----------\n");
                   3670:       printf("... current parameter settings ...\n");
                   3671:       printf("... scaling ... %20.10e\n", scbd);
                   3672:       printf("...   tol   ... %20.10e\n", t);
                   3673:       printf("... maxstep ... %20.10e\n", h);
                   3674:       printf("...   illc  ... %20u\n", illc);
                   3675:       printf("...   ktm   ... %20u\n", ktm);
                   3676:       printf("... maxfun  ... %20u\n", maxfun);
                   3677:    }
                   3678:    if (prin) print2();
                   3679: 
                   3680: mloop:
                   3681:     biter++;  /* Added to count the loops */
                   3682:    /* sf = d[0]; */
                   3683:    /* s = d[0] = 0.0; */
                   3684:     printf("\n Big iteration %d \n",biter);
                   3685:     fprintf(ficlog,"\n Big iteration %d \n",biter);
                   3686:     sf = d[1];
                   3687:    s = d[1] = 0.0;
                   3688: 
                   3689:    /* minimize along first direction V(*,1) */
                   3690: #ifdef DEBUGPRAX
                   3691:    printf("  Minimize along the first direction V(*,1). illc=%d\n",illc);
                   3692:    /* fprintf(ficlog,"  Minimize along the first direction V(*,1).\n"); */
                   3693: #endif
                   3694: #ifdef DEBUGPRAX2
                   3695:    printf("praxis4 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3696: #endif
                   3697:    /* min(0, 2, &d[0], &s, fx, 0); /\* mac heps not global *\/ */
                   3698:    minny(1, 2, &d[1], &s, fx, 0); /* mac heps not global */
                   3699: #ifdef DEBUGPRAX
                   3700:    printf("praxis5 macheps=%14g h=%14g looks at sign of s=%14g fx=%14g\n",macheps,h, s,fx); 
                   3701: #endif
                   3702:    if (s <= 0.0)
                   3703:       /* for (i=0; i < n; i++) */
                   3704:       for (i=1; i <= n; i++)
                   3705:           v[i][1] = -v[i][1];
                   3706:    /* if ((sf <= (0.9 * d[0])) || ((0.9 * sf) >= d[0])) */
                   3707:    if ((sf <= (0.9 * d[1])) || ((0.9 * sf) >= d[1]))
                   3708:       /* for (i=1; i<n; i++) */
                   3709:       for (i=2; i<=n; i++)
                   3710:           d[i] = 0.0;
                   3711:    /* for (k=1; k<n; k++) { */
                   3712:    for (k=2; k<=n; k++) {
                   3713:     /*
                   3714:       The inner loop starts here.
                   3715:     */
                   3716: #ifdef DEBUGPRAX
                   3717:       printf("      The inner loop  here from k=%d to n=%d.\n",k,n);
                   3718:       /* fprintf(ficlog,"      The inner loop  here from k=%d to n=%d.\n",k,n); */
                   3719: #endif
                   3720:        /* for (i=0; i<n; i++) */
                   3721:        for (i=1; i<=n; i++)
                   3722:            y[i] = x[i];
                   3723:        sf = fx;
                   3724: #ifdef DEBUGPRAX
                   3725:        printf(" illc=%d and kt=%d and ktm=%d\n", illc, kt, ktm);
                   3726: #endif
                   3727:        illc = illc || (kt > 0);
                   3728: next:
                   3729:        kl = k;
                   3730:        df = 0.0;
                   3731:        if (illc) {        /* random step to get off resolution valley */
                   3732: #ifdef DEBUGPRAX
                   3733:          printf("  A random step follows, to avoid resolution valleys.\n");
                   3734:          matprint("  before rand, vectors:",v,n,n);
                   3735: #endif
                   3736:           for (i=1; i<=n; i++) {
                   3737: #ifdef NOBRENTRAND
                   3738:            r = drandom();
                   3739: #else
                   3740:            seed=i;
                   3741:            /* seed=i+1; */
                   3742: #ifdef DEBUGRAND
                   3743:            printf(" Random seed=%d, brent i=%d",seed,i); /* YYYY i=5 j=1 vji= -0.0001170073 */
                   3744: #endif
                   3745:            r = randbrent ( &seed );
                   3746: #endif
                   3747: #ifdef DEBUGRAND
                   3748:            printf(" Random r=%.7g \n",r);
                   3749: #endif     
                   3750:             z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (r - 0.5);
                   3751:            /* z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (drandom() - 0.5); */
                   3752: 
                   3753:            s = z[i];
                   3754:               for (j=1; j <= n; j++)
                   3755:                   x[j] += s * v[j][i];
                   3756:          }
                   3757: #ifdef DEBUGRAND
                   3758:          matprint("  after rand, vectors:",v,n,n);
                   3759: #endif
                   3760: #ifdef NR_SHIFT
                   3761:           fx = (*fun)((x-1), n);
                   3762: #else
                   3763:           fx = (*fun)(x, n);
                   3764: #endif
                   3765:           /* fx = (*func) ( (x-1) ); *//* This for func which is computed from x[1] and not from x[0] xm1=(x-1)*/
                   3766:           nf++;
                   3767:        }
                   3768:        /* minimize along non-conjugate directions */
                   3769: #ifdef DEBUGPRAX
                   3770:        printf(" Minimize along the 'non-conjugate' directions (dots printed) V(*,%d),...,V(*,%d).\n",k,n);
                   3771:        /* fprintf(ficlog," Minimize along the 'non-conjugate' directions  (dots printed) V(*,%d),...,V(*,%d).\n",k,n); */
                   3772: #endif
                   3773:        /* for (k2=k; k2<n; k2++) {  /\* Be careful here k2 <=n ? *\/ */
                   3774:        for (k2=k; k2<=n; k2++) {  /* Be careful here k2 <=n ? */
                   3775:            sl = fx;
                   3776:            s = 0.0;
                   3777: #ifdef DEBUGPRAX
                   3778:           printf(" Minimize along the 'NON-CONJUGATE' true direction k2=%14d fx=%14.7f\n",k2, fx);
                   3779:    matprint("  before min vectors:",v,n,n);
                   3780: #endif
                   3781:            /* min(k2, 2, &d[k2], &s, fx, 0); */
                   3782:    /*    jsearch=k2-1; */
                   3783:    /* min(jsearch, 2, &d[jsearch], &s, fx, 0); */
                   3784:    minny(k2, 2, &d[k2], &s, fx, 0);
                   3785: #ifdef DEBUGPRAX
                   3786:           printf(" . D(%d)=%14.7f d[k2]=%14.7f z[k2]=%14.7f illc=%14d fx=%14.7f\n",k2,d[k2],d[k2],z[k2],illc,fx);
                   3787: #endif
                   3788:           if (illc) {
                   3789:              /* double szk = s + z[k2]; */
                   3790:               /* s = d[k2] * szk*szk; */
                   3791:              double szk = s + z[k2];
                   3792:               s = d[k2] * szk*szk;
                   3793:           }
                   3794:            else 
                   3795:              s = sl - fx;
                   3796:            /* if (df < s) { */
                   3797:            if (df <= s) {
                   3798:               df = s;
                   3799:               kl = k2;
                   3800: #ifdef DEBUGPRAX
                   3801:            printf(" df=%.7g and choose kl=%d \n",df,kl); /* UUUU */
                   3802: #endif
                   3803:            }
                   3804:        } /* end loop k2 */
                   3805:         /*
                   3806:          If there was not much improvement on the first try, set
                   3807:          ILLC = true and start the inner loop again.
                   3808:        */
                   3809: #ifdef DEBUGPRAX
                   3810:        printf(" If there was not much improvement on the first try, set ILLC = true and start the inner loop again. illc=%d\n",illc);
                   3811:        /* fprintf(ficlog,"  If there was not much improvement on the first try, set ILLC = true and start the inner loop again.\n"); */
                   3812: #endif
                   3813:         if (!illc && (df < fabs(100.0 * (macheps) * fx))) {
                   3814: #ifdef DEBUGPRAX
                   3815:          printf("\n NO SUCCESS because DF is small, starts inner loop with same K(=%d), fabs(  100.0 * machep(=%.10e) * fx(=%.9e) )=%.9e > df(=%.9e) break illc=%d\n", k, macheps, fx, fabs ( 100.0 * macheps * fx ), df, illc);         
                   3816: #endif
                   3817:           illc = 1;
                   3818:           goto next;
                   3819:        }
                   3820: #ifdef DEBUGPRAX
                   3821:        printf("\n SUCCESS, BREAKS inner loop K(=%d) because DF is big, fabs(  100.0 * machep(=%.10e) * fx(=%.9e) )=%.9e <= df(=%.9e) break illc=%d\n", k, macheps, fx, fabs ( 100.0 * macheps * fx ), df, illc);
                   3822: #endif
                   3823:        
                   3824:        /* if ((k == 1) && (prin > 1)){ /\* be careful k=2 *\/ */
                   3825:        if ((k == 2) && (prin > 1)){ /* be careful k=2 */
                   3826: #ifdef DEBUGPRAX
                   3827:         printf("  NEW D The second difference array d:\n" );
                   3828:         /* fprintf(ficlog, " NEW D The second difference array d:\n" ); */
                   3829: #endif
                   3830:         vecprint(" NEW D The second difference array d:",d,n);
                   3831:        }
                   3832:        /* minimize along conjugate directions */ 
                   3833:        /*
                   3834:         Minimize along the "conjugate" directions V(*,1),...,V(*,K-1).
                   3835:        */
                   3836: #ifdef DEBUGPRAX
                   3837:       printf("Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1);
                   3838:       /* fprintf(ficlog,"Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1); */
                   3839: #endif
                   3840:       /* for (k2=0; k2<=k-1; k2++) { */
                   3841:       for (k2=1; k2<=k-1; k2++) {
                   3842:            s = 0.0;
                   3843:            /* min(k2-1, 2, &d[k2-1], &s, fx, 0); */
                   3844:            minny(k2, 2, &d[k2], &s, fx, 0);
                   3845:        }
                   3846:        f1 = fx;
                   3847:        fx = sf;
                   3848:        lds = 0.0;
                   3849:        /* for (i=0; i<n; i++) { */
                   3850:        for (i=1; i<=n; i++) {
                   3851:            sl = x[i];
                   3852:            x[i] = y[i];
                   3853:            y[i] = sl - y[i];
                   3854:            sl = y[i];
                   3855:            lds = lds + sl*sl;
                   3856:        }
                   3857:        lds = sqrt(lds);
                   3858: #ifdef DEBUGPRAX
                   3859:        printf("Minimization done 'conjugate', shifted all points, computed lds=%.8f\n",lds);
                   3860: #endif      
                   3861:       /*
                   3862:        Discard direction V(*,kl).
                   3863:        
                   3864:        If no random step was taken, V(*,KL) is the "non-conjugate"
                   3865:        direction along which the greatest improvement was made.
                   3866:       */
                   3867:        if (lds > small_windows) {
                   3868: #ifdef DEBUGPRAX
                   3869:        printf("lds big enough to throw direction  V(*,kl=%d). If no random step was taken, V(*,KL) is the 'non-conjugate' direction along which the greatest improvement was made.\n",kl);
                   3870:         matprint("  before shift new conjugate vectors:",v,n,n);
                   3871: #endif
                   3872:         for (i=kl-1; i>=k; i--) {
                   3873:           /* for (j=0; j < n; j++) */
                   3874:           for (j=1; j <= n; j++)
                   3875:             /* v[j][i+1] = v[j][i]; */ /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3876:             v[j][i+1] = v[j][i]; /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3877:           /* v[j][i+1] = v[j][i]; */
                   3878:           /* d[i+1] = d[i];*/  /* last  is d[k+1]= d[k] */
                   3879:           d[i+1] = d[i];  /* last  is d[k]= d[k-1] */
                   3880:         }
                   3881: #ifdef DEBUGPRAX
                   3882:         matprint("  after shift new conjugate vectors:",v,n,n);         
                   3883: #endif  /* d[k] = 0.0; */
                   3884:         d[k] = 0.0;
                   3885:         for (i=1; i <= n; i++)
                   3886:           v[i][k] = y[i] / lds;
                   3887:         /* v[i][k] = y[i] / lds; */
                   3888: #ifdef DEBUGPRAX
                   3889:         printf("Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x). d2=%14.7g lds=%.10f\n",k,d[k],lds);
                   3890:         /* fprintf(ficlog,"Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x).\n",k); */
                   3891:     matprint("  before min new conjugate vectors:",v,n,n);      
                   3892: #endif
                   3893:         /* min(k-1, 4, &d[k-1], &lds, f1, 1); */
                   3894:         minny(k, 4, &d[k], &lds, f1, 1);
                   3895: #ifdef DEBUGPRAX
                   3896:         printf(" after min d(k)=%d %.7g lds=%14f\n",k,d[k],lds);
                   3897:    matprint("  after min vectors:",v,n,n);
                   3898: #endif
                   3899:         if (lds <= 0.0) {
                   3900:           lds = -lds;
                   3901: #ifdef DEBUGPRAX
                   3902:          printf(" lds changed sign lds=%.14f k=%d\n",lds,k);
                   3903: #endif    
                   3904:           /* for (i=0; i<n; i++) */
                   3905:           /*   v[i][k] = -v[i][k]; */
                   3906:           for (i=1; i<=n; i++)
                   3907:             v[i][k] = -v[i][k];
                   3908:         }
                   3909:        }
                   3910:        ldt = ldfac * ldt;
                   3911:        if (ldt < lds)
                   3912:           ldt = lds;
                   3913:        if (prin > 0){
                   3914: #ifdef DEBUGPRAX
                   3915:        printf(" k=%d",k);
                   3916:        /* fprintf(ficlog," k=%d",k); */
                   3917: #endif
                   3918:        print2();/* n, x, prin, fx, nf, nl ); */
                   3919:        }
                   3920:        t2 = 0.0;
                   3921:        /* for (i=0; i<n; i++) */
                   3922:        for (i=1; i<=n; i++)
                   3923:            t2 += x[i]*x[i];
                   3924:        t2 = m2 * sqrt(t2) + t;
                   3925:        /*
                   3926:        See whether the length of the step taken since starting the
                   3927:        inner loop exceeds half the tolerance.
                   3928:       */
                   3929: #ifdef DEBUGPRAX
                   3930:        printf("See if step length exceeds half the tolerance.\n"); /* ZZZZZ */
                   3931:       /* fprintf(ficlog,"See if step length exceeds half the tolerance.\n"); */
                   3932: #endif
                   3933:        if (ldt > (0.5 * t2))
                   3934:           kt = 0;
                   3935:        else 
                   3936:          kt++;
                   3937: #ifdef DEBUGPRAX
                   3938:        printf("if kt=%d >? ktm=%d gotoL2 loop\n",kt,ktm);
                   3939: #endif
                   3940:        if (kt > ktm){
                   3941:          if ( 0 < prin ){
                   3942:           /* printf("\nr8vec_print\n X:\n"); */
                   3943:           /* fprintf(ficlog,"\nr8vec_print\n X:\n"); */
                   3944:           vecprint ("END  X:", x, n );
                   3945:         }
                   3946:            goto fret;
                   3947:        }
                   3948: #ifdef DEBUGPRAX
                   3949:    matprint("  end of L2 loop vectors:",v,n,n);
                   3950: #endif
                   3951:        
                   3952:    }
                   3953:    /* printf("The inner loop ends here.\n"); */
                   3954:    /* fprintf(ficlog,"The inner loop ends here.\n"); */
                   3955:    /*
                   3956:      The inner loop ends here.
                   3957:      
                   3958:      Try quadratic extrapolation in case we are in a curved valley.
                   3959:    */
                   3960: #ifdef DEBUGPRAX
                   3961:    printf("Try QUAD ratic extrapolation in case we are in a curved valley.\n");
                   3962: #endif
                   3963:    /*  try quadratic extrapolation in case    */
                   3964:    /*  we are stuck in a curved valley        */
                   3965:    quad();
                   3966:    dn = 0.0;
                   3967:    /* for (i=0; i<n; i++) { */
                   3968:    for (i=1; i<=n; i++) {
                   3969:        d[i] = 1.0 / sqrt(d[i]);
                   3970:        if (dn < d[i])
                   3971:           dn = d[i];
                   3972:    }
                   3973:    if (prin > 2)
                   3974:      matprint("  NEW DIRECTIONS vectors:",v,n,n);
                   3975:    /* for (j=0; j<n; j++) { */
                   3976:    for (j=1; j<=n; j++) {
                   3977:        s = d[j] / dn;
                   3978:        /* for (i=0; i < n; i++) */
                   3979:        for (i=1; i <= n; i++)
                   3980:            v[i][j] *= s;
                   3981:    }
                   3982:    
                   3983:    if (scbd > 1.0) {       /* scale axis to reduce condition number */
                   3984: #ifdef DEBUGPRAX
                   3985:      printf("Scale the axes to try to reduce the condition number.\n");
                   3986: #endif
                   3987:      /* fprintf(ficlog,"Scale the axes to try to reduce the condition number.\n"); */
                   3988:       s = vlarge;
                   3989:       /* for (i=0; i<n; i++) { */
                   3990:       for (i=1; i<=n; i++) {
                   3991:           sl = 0.0;
                   3992:           /* for (j=0; j < n; j++) */
                   3993:           for (j=1; j <= n; j++)
                   3994:               sl += v[i][j]*v[i][j];
                   3995:           z[i] = sqrt(sl);
                   3996:           if (z[i] < m4)
                   3997:              z[i] = m4;
                   3998:           if (s > z[i])
                   3999:              s = z[i];
                   4000:       }
                   4001:       /* for (i=0; i<n; i++) { */
                   4002:       for (i=1; i<=n; i++) {
                   4003:           sl = s / z[i];
                   4004:           z[i] = 1.0 / sl;
                   4005:           if (z[i] > scbd) {
                   4006:              sl = 1.0 / scbd;
                   4007:              z[i] = scbd;
                   4008:           }
                   4009:       }
                   4010:    }
                   4011:    for (i=1; i<=n; i++)
                   4012:        /* for (j=0; j<=i-1; j++) { */
                   4013:        /* for (j=1; j<=i; j++) { */
                   4014:        for (j=1; j<=i-1; j++) {
                   4015:            s = v[i][j];
                   4016:            v[i][j] = v[j][i];
                   4017:            v[j][i] = s;
                   4018:        }
                   4019: #ifdef DEBUGPRAX
                   4020:     printf(" Calculate a new set of orthogonal directions before repeating  the main loop.\n  Transpose V for MINFIT:...\n");
                   4021: #endif
                   4022:       /*
                   4023:       MINFIT finds the singular value decomposition of V.
                   4024: 
                   4025:       This gives the principal values and principal directions of the
                   4026:       approximating quadratic form without squaring the condition number.
                   4027:     */
                   4028:  #ifdef DEBUGPRAX
                   4029:     printf(" MINFIT finds the singular value decomposition of V. \n This gives the principal values and principal directions of the\n  approximating quadratic form without squaring the condition number...\n");
                   4030: #endif
                   4031: 
                   4032:    minfit(n, macheps, vsmall, v, d);
                   4033:     /* for(i=0; i<n;i++)printf(" %14.7g",d[i]); */
                   4034:     /* v is overwritten with R. */
                   4035:     /*
                   4036:       Unscale the axes.
                   4037:     */
                   4038:    if (scbd > 1.0) {
                   4039: #ifdef DEBUGPRAX
                   4040:       printf(" Unscale the axes.\n");
                   4041: #endif
                   4042:       /* for (i=0; i<n; i++) { */
                   4043:       for (i=1; i<=n; i++) {
                   4044:           s = z[i];
                   4045:           /* for (j=0; j<n; j++) */
                   4046:           for (j=1; j<=n; j++)
                   4047:               v[i][j] *= s;
                   4048:       }
                   4049:       /* for (i=0; i<n; i++) { */
                   4050:       for (i=1; i<=n; i++) {
                   4051:           s = 0.0;
                   4052:           /* for (j=0; j<n; j++) */
                   4053:           for (j=1; j<=n; j++)
                   4054:               s += v[j][i]*v[j][i];
                   4055:           s = sqrt(s);
                   4056:           d[i] *= s;
                   4057:           s = 1.0 / s;
                   4058:           /* for (j=0; j<n; j++) */
                   4059:           for (j=1; j<=n; j++)
                   4060:               v[j][i] *= s;
                   4061:       }
                   4062:    }
                   4063:    /* for (i=0; i<n; i++) { */
                   4064:    double dni; /* added for compatibility with buckhardt but not brent */
                   4065:    for (i=1; i<=n; i++) {
                   4066:      dni=dn*d[i]; /* added for compatibility with buckhardt but not brent */
                   4067:        if ((dn * d[i]) > large)
                   4068:           d[i] = vsmall;
                   4069:        else if ((dn * d[i]) < small_windows)
                   4070:           d[i] = vlarge;
                   4071:        else 
                   4072:         d[i] = 1.0 / dni / dni; /* added for compatibility with buckhardt but not brent */
                   4073:           /* d[i] = pow(dn * d[i],-2.0); */
                   4074:    }
                   4075: #ifdef DEBUGPRAX
                   4076:    vecprint ("\n Before sort Eigenvalues of a:",d,n );
                   4077: #endif
                   4078:    
                   4079:    sort();               /* the new eigenvalues and eigenvectors */
                   4080: #ifdef DEBUGPRAX
                   4081:    vecprint( " After sort the eigenvalues ....\n", d, n);
                   4082:    matprint( " After sort the eigenvectors....\n", v, n,n);
                   4083: #endif
                   4084: #ifdef DEBUGPRAX
                   4085:     printf("  Determine the smallest eigenvalue.\n");
                   4086: #endif
                   4087:    /* dmin = d[n-1]; */
                   4088:    dmin = d[n];
                   4089:    if (dmin < small_windows)
                   4090:       dmin = small_windows;
                   4091:     /*
                   4092:      The ratio of the smallest to largest eigenvalue determines whether
                   4093:      the system is ill conditioned.
                   4094:    */
                   4095:   
                   4096:    /* illc = (m2 * d[0]) > dmin; */
                   4097:    illc = (m2 * d[1]) > dmin;
                   4098: #ifdef DEBUGPRAX
                   4099:     printf("  The ratio of the smallest to largest eigenvalue determines whether\n  the system is ill conditioned=%d . dmin=%.10lf < m2=%.10lf * d[1]=%.10lf \n",illc, dmin,m2, d[1]);
                   4100: #endif
                   4101:    
                   4102:    if ((prin > 2) && (scbd > 1.0))
                   4103:       vecprint("\n The scale factors:",z,n);
                   4104:    if (prin > 2)
                   4105:       vecprint("  Principal values (EIGEN VALUES OF A) of the quadratic form:",d,n);
                   4106:    if (prin > 2)
                   4107:      matprint("  The principal axes (EIGEN VECTORS OF A:",v,n, n);
                   4108: 
                   4109:    if ((maxfun > 0) && (nf > maxfun)) {
                   4110:       if (prin)
                   4111:         printf("\n... maximum number of function calls reached ...\n");
                   4112:       goto fret;
                   4113:    }
                   4114: #ifdef DEBUGPRAX
                   4115:    printf("Goto main loop\n");
                   4116: #endif
                   4117:    goto mloop;          /* back to main loop */
                   4118: 
                   4119: fret:
                   4120:    if (prin > 0) {
                   4121:          vecprint("\n  X:", x, n);
                   4122:          /* printf("\n... ChiSq reduced to %20.10e ...\n", fx); */
                   4123:         /* printf("... after %20u function calls.\n", nf); */
                   4124:    }
                   4125:    free_vector(d, 1, n);
                   4126:    free_vector(y, 1, n);
                   4127:    free_vector(z, 1, n);
                   4128:    free_vector(q0, 1, n);
                   4129:    free_vector(q1, 1, n);
                   4130:    free_matrix(v, 1, n, 1, n);
                   4131:    /*   double *d, *y, *z, */
                   4132:    /* *q0, *q1, **v; */
                   4133:    free_vector(tflin, 1, n);
                   4134:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   4135:    free_vector(e, 1, n);
                   4136:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   4137:    
                   4138:    return(fx);
                   4139: }
                   4140: 
                   4141: /* end praxis gegen */
1.126     brouard  4142: 
                   4143: /*************** powell ************************/
1.162     brouard  4144: /*
1.317     brouard  4145: Minimization of a function func of n variables. Input consists in an initial starting point
                   4146: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   4147: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   4148: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  4149: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   4150: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   4151:  */
1.224     brouard  4152: #ifdef LINMINORIGINAL
                   4153: #else
                   4154:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  4155:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  4156: #endif
1.126     brouard  4157: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   4158:            double (*func)(double [])) 
                   4159: { 
1.224     brouard  4160: #ifdef LINMINORIGINAL
                   4161:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  4162:              double (*func)(double [])); 
1.224     brouard  4163: #else 
1.241     brouard  4164:  void linmin(double p[], double xi[], int n, double *fret,
                   4165:             double (*func)(double []),int *flat); 
1.224     brouard  4166: #endif
1.239     brouard  4167:  int i,ibig,j,jk,k; 
1.126     brouard  4168:   double del,t,*pt,*ptt,*xit;
1.181     brouard  4169:   double directest;
1.126     brouard  4170:   double fp,fptt;
                   4171:   double *xits;
                   4172:   int niterf, itmp;
1.349     brouard  4173:   int Bigter=0, nBigterf=1;
                   4174:   
1.126     brouard  4175:   pt=vector(1,n); 
                   4176:   ptt=vector(1,n); 
                   4177:   xit=vector(1,n); 
                   4178:   xits=vector(1,n); 
                   4179:   *fret=(*func)(p); 
                   4180:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  4181:   rcurr_time = time(NULL);
                   4182:   fp=(*fret); /* Initialisation */
1.126     brouard  4183:   for (*iter=1;;++(*iter)) { 
                   4184:     ibig=0; 
                   4185:     del=0.0; 
1.157     brouard  4186:     rlast_time=rcurr_time;
1.349     brouard  4187:     rlast_btime=rcurr_time;
1.157     brouard  4188:     /* (void) gettimeofday(&curr_time,&tzp); */
                   4189:     rcurr_time = time(NULL);  
                   4190:     curr_time = *localtime(&rcurr_time);
1.337     brouard  4191:     /* 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); */
                   4192:     /* 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.359     brouard  4193:     /* Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /\* Big iteration, i.e on ncovmodel cycle *\/ */
                   4194:     Bigter=(*iter - (*iter-1) % n)/n +1; /* Big iteration, i.e on ncovmodel cycle */
1.349     brouard  4195:     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);
                   4196:     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);
                   4197:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  4198:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  4199:     for (i=1;i<=n;i++) {
1.126     brouard  4200:       fprintf(ficrespow," %.12lf", p[i]);
                   4201:     }
1.239     brouard  4202:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   4203:     printf("\n#model=  1      +     age ");
                   4204:     fprintf(ficlog,"\n#model=  1      +     age ");
                   4205:     if(nagesqr==1){
1.241     brouard  4206:        printf("  + age*age  ");
                   4207:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  4208:     }
                   4209:     for(j=1;j <=ncovmodel-2;j++){
                   4210:       if(Typevar[j]==0) {
                   4211:        printf("  +      V%d  ",Tvar[j]);
                   4212:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   4213:       }else if(Typevar[j]==1) {
                   4214:        printf("  +    V%d*age ",Tvar[j]);
                   4215:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   4216:       }else if(Typevar[j]==2) {
                   4217:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4218:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  4219:       }else if(Typevar[j]==3) {
                   4220:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4221:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  4222:       }
                   4223:     }
1.126     brouard  4224:     printf("\n");
1.239     brouard  4225: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   4226: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  4227:     fprintf(ficlog,"\n");
1.239     brouard  4228:     for(i=1,jk=1; i <=nlstate; i++){
                   4229:       for(k=1; k <=(nlstate+ndeath); k++){
                   4230:        if (k != i) {
                   4231:          printf("%d%d ",i,k);
                   4232:          fprintf(ficlog,"%d%d ",i,k);
                   4233:          for(j=1; j <=ncovmodel; j++){
                   4234:            printf("%12.7f ",p[jk]);
                   4235:            fprintf(ficlog,"%12.7f ",p[jk]);
                   4236:            jk++; 
                   4237:          }
                   4238:          printf("\n");
                   4239:          fprintf(ficlog,"\n");
                   4240:        }
                   4241:       }
                   4242:     }
1.241     brouard  4243:     if(*iter <=3 && *iter >1){
1.157     brouard  4244:       tml = *localtime(&rcurr_time);
                   4245:       strcpy(strcurr,asctime(&tml));
                   4246:       rforecast_time=rcurr_time; 
1.126     brouard  4247:       itmp = strlen(strcurr);
                   4248:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  4249:        strcurr[itmp-1]='\0';
1.162     brouard  4250:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  4251:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  4252:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   4253:        niterf=nBigterf*ncovmodel;
                   4254:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  4255:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   4256:        forecast_time = *localtime(&rforecast_time);
                   4257:        strcpy(strfor,asctime(&forecast_time));
                   4258:        itmp = strlen(strfor);
                   4259:        if(strfor[itmp-1]=='\n')
                   4260:          strfor[itmp-1]='\0';
1.349     brouard  4261:        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);
                   4262:        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  4263:       }
                   4264:     }
1.359     brouard  4265:     for (i=1;i<=n;i++) { /* For each direction i, maximisation after loading directions */
                   4266:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales. xi is not changed but one dim xit  */
                   4267: 
                   4268:       fptt=(*fret); /* Computes likelihood for parameters xit */
1.126     brouard  4269: #ifdef DEBUG
1.203     brouard  4270:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   4271:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  4272: #endif
1.203     brouard  4273:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  4274:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  4275: #ifdef LINMINORIGINAL
1.359     brouard  4276:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction xit, i has coordinates p[j].*/
1.357     brouard  4277:       /* xit[j] gives the n coordinates of direction i as input.*/
                   4278:       /* *fret gives the maximum value on direction xit */
1.224     brouard  4279: #else
                   4280:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.359     brouard  4281:       flatdir[i]=flat; /* Function is vanishing in that direction i */
1.224     brouard  4282: #endif
1.359     brouard  4283:       /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  4284:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.359     brouard  4285:        /* because that direction will be replaced unless the gain del is small */
                   4286:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   4287:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   4288:        /* with the new direction. */
                   4289:        del=fabs(fptt-(*fret)); 
                   4290:        ibig=i; 
1.126     brouard  4291:       } 
                   4292: #ifdef DEBUG
                   4293:       printf("%d %.12e",i,(*fret));
                   4294:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   4295:       for (j=1;j<=n;j++) {
1.359     brouard  4296:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   4297:        printf(" x(%d)=%.12e",j,xit[j]);
                   4298:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  4299:       }
                   4300:       for(j=1;j<=n;j++) {
1.359     brouard  4301:        printf(" p(%d)=%.12e",j,p[j]);
                   4302:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  4303:       }
                   4304:       printf("\n");
                   4305:       fprintf(ficlog,"\n");
                   4306: #endif
1.187     brouard  4307:     } /* end loop on each direction i */
1.357     brouard  4308:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  4309:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.359     brouard  4310:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  4311:     for(j=1;j<=n;j++) {
                   4312:       if(flatdir[j] >0){
                   4313:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   4314:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  4315:       }
1.319     brouard  4316:       /* printf("\n"); */
                   4317:       /* fprintf(ficlog,"\n"); */
                   4318:     }
1.243     brouard  4319:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   4320:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  4321:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   4322:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   4323:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   4324:       /* decreased of more than 3.84  */
                   4325:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   4326:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   4327:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  4328:                        
1.188     brouard  4329:       /* Starting the program with initial values given by a former maximization will simply change */
                   4330:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   4331:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   4332:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  4333: #ifdef DEBUG
                   4334:       int k[2],l;
                   4335:       k[0]=1;
                   4336:       k[1]=-1;
                   4337:       printf("Max: %.12e",(*func)(p));
                   4338:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   4339:       for (j=1;j<=n;j++) {
                   4340:        printf(" %.12e",p[j]);
                   4341:        fprintf(ficlog," %.12e",p[j]);
                   4342:       }
                   4343:       printf("\n");
                   4344:       fprintf(ficlog,"\n");
                   4345:       for(l=0;l<=1;l++) {
                   4346:        for (j=1;j<=n;j++) {
                   4347:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   4348:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4349:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4350:        }
                   4351:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4352:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4353:       }
                   4354: #endif
                   4355: 
                   4356:       free_vector(xit,1,n); 
                   4357:       free_vector(xits,1,n); 
                   4358:       free_vector(ptt,1,n); 
                   4359:       free_vector(pt,1,n); 
                   4360:       return; 
1.192     brouard  4361:     } /* enough precision */ 
1.240     brouard  4362:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.359     brouard  4363:     for (j=1;j<=n;j++) { /* Computes the extrapolated point and value f3, P_0 + 2 (P_n-P_0)=2Pn-P0 and xit is direction Pn-P0 */
1.126     brouard  4364:       ptt[j]=2.0*p[j]-pt[j]; 
1.359     brouard  4365:       xit[j]=p[j]-pt[j]; /* Coordinate j of last direction xi_n=P_n-P_0 */
                   4366: #ifdef DEBUG
                   4367:       printf("\n %d xit=%12.7g p=%12.7g pt=%12.7g ",j,xit[j],p[j],pt[j]);
                   4368: #endif
                   4369:       pt[j]=p[j]; /* New P0 is Pn */
                   4370:     }
                   4371: #ifdef DEBUG
                   4372:     printf("\n");
                   4373: #endif
1.181     brouard  4374:     fptt=(*func)(ptt); /* f_3 */
1.359     brouard  4375: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in directions until some iterations are done */
1.224     brouard  4376:                if (*iter <=4) {
1.225     brouard  4377: #else
                   4378: #endif
1.224     brouard  4379: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  4380: #else
1.161     brouard  4381:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  4382: #endif
1.162     brouard  4383:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  4384:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  4385:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   4386:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   4387:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  4388:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   4389:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   4390:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  4391:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  4392:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   4393:       /* mu² and del² are equal when f3=f1 */
1.359     brouard  4394:       /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   4395:       /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   4396:       /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   4397:       /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  4398: #ifdef NRCORIGINAL
                   4399:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   4400: #else
                   4401:       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  4402:       t= t- del*SQR(fp-fptt);
1.183     brouard  4403: #endif
1.202     brouard  4404:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  4405: #ifdef DEBUG
1.181     brouard  4406:       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);
                   4407:       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  4408:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4409:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4410:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4411:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4412:       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);
                   4413:       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);
                   4414: #endif
1.183     brouard  4415: #ifdef POWELLORIGINAL
                   4416:       if (t < 0.0) { /* Then we use it for new direction */
1.361   ! brouard  4417: #else  /* Not POWELLOriginal but Brouard's */
1.182     brouard  4418:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.359     brouard  4419:        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  4420:         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  4421:         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  4422:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   4423:       } 
1.361   ! brouard  4424:       if (directest < 0.0) { /* Then we use (P0, Pn) for new direction Xi_n or Xi_iBig */
1.181     brouard  4425: #endif
1.191     brouard  4426: #ifdef DEBUGLINMIN
1.234     brouard  4427:        printf("Before linmin in direction P%d-P0\n",n);
                   4428:        for (j=1;j<=n;j++) {
                   4429:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4430:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4431:          if(j % ncovmodel == 0){
                   4432:            printf("\n");
                   4433:            fprintf(ficlog,"\n");
                   4434:          }
                   4435:        }
1.224     brouard  4436: #endif
                   4437: #ifdef LINMINORIGINAL
1.234     brouard  4438:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  4439: #else
1.234     brouard  4440:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   4441:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  4442: #endif
1.234     brouard  4443:        
1.191     brouard  4444: #ifdef DEBUGLINMIN
1.234     brouard  4445:        for (j=1;j<=n;j++) { 
                   4446:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4447:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4448:          if(j % ncovmodel == 0){
                   4449:            printf("\n");
                   4450:            fprintf(ficlog,"\n");
                   4451:          }
                   4452:        }
1.224     brouard  4453: #endif
1.234     brouard  4454:        for (j=1;j<=n;j++) { 
                   4455:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   4456:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   4457:        }
1.361   ! brouard  4458: 
        !          4459: /* #else */
        !          4460: /*     for (i=1;i<=n-1;i++) {  */
        !          4461: /*       for (j=1;j<=n;j++) {  */
        !          4462: /*         xi[j][i]=xi[j][i+1]; /\* Standard method of conjugate directions, not Powell who changes the nth direction by p0 pn . *\/ */
        !          4463: /*       } */
        !          4464: /*     } */
        !          4465: /*     for (j=1;j<=n;j++) {  */
        !          4466: /*       xi[j][n]=xit[j];      /\* and this nth direction by the by the average p_0 p_n *\/ */
        !          4467: /*     } */
        !          4468: /*     /\* for (j=1;j<=n-1;j++) {  *\/ */
        !          4469: /*     /\*   xi[j][1]=xi[j][j+1]; /\\* Standard method of conjugate directions *\\/ *\/ */
        !          4470: /*     /\*   xi[j][n]=xit[j];      /\\* and this nth direction by the by the average p_0 p_n *\\/ *\/ */
        !          4471: /*     /\* } *\/ */
        !          4472: /* #endif */
1.224     brouard  4473: #ifdef LINMINORIGINAL
                   4474: #else
1.234     brouard  4475:        for (j=1, flatd=0;j<=n;j++) {
                   4476:          if(flatdir[j]>0)
                   4477:            flatd++;
                   4478:        }
                   4479:        if(flatd >0){
1.255     brouard  4480:          printf("%d flat directions: ",flatd);
                   4481:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  4482:          for (j=1;j<=n;j++) { 
                   4483:            if(flatdir[j]>0){
                   4484:              printf("%d ",j);
                   4485:              fprintf(ficlog,"%d ",j);
                   4486:            }
                   4487:          }
                   4488:          printf("\n");
                   4489:          fprintf(ficlog,"\n");
1.319     brouard  4490: #ifdef FLATSUP
                   4491:           free_vector(xit,1,n); 
                   4492:           free_vector(xits,1,n); 
                   4493:           free_vector(ptt,1,n); 
                   4494:           free_vector(pt,1,n); 
                   4495:           return;
                   4496: #endif
1.361   ! brouard  4497:        }  /* endif(flatd >0) */
        !          4498: #endif /* LINMINORIGINAL */
1.234     brouard  4499:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4500:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4501:        
1.126     brouard  4502: #ifdef DEBUG
1.234     brouard  4503:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4504:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4505:        for(j=1;j<=n;j++){
                   4506:          printf(" %lf",xit[j]);
                   4507:          fprintf(ficlog," %lf",xit[j]);
                   4508:        }
                   4509:        printf("\n");
                   4510:        fprintf(ficlog,"\n");
1.126     brouard  4511: #endif
1.192     brouard  4512:       } /* end of t or directest negative */
1.359     brouard  4513:       printf(" Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
                   4514:       fprintf(ficlog," Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
1.224     brouard  4515: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  4516: #else
1.234     brouard  4517:       } /* end if (fptt < fp)  */
1.192     brouard  4518: #endif
1.225     brouard  4519: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  4520:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  4521: #else
1.224     brouard  4522: #endif
1.234     brouard  4523:                } /* loop iteration */ 
1.126     brouard  4524: } 
1.234     brouard  4525:   
1.126     brouard  4526: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  4527:   
1.235     brouard  4528:   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  4529:   {
1.338     brouard  4530:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  4531:      *   (and selected quantitative values in nres)
                   4532:      *  by left multiplying the unit
                   4533:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   4534:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   4535:      * Wx is row vector: population in state 1, population in state 2, population dead
                   4536:      * or prevalence in state 1, prevalence in state 2, 0
                   4537:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   4538:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   4539:      * Output is prlim.
                   4540:      * Initial matrix pimij 
                   4541:      */
1.206     brouard  4542:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4543:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4544:   /*  0,                   0                  , 1} */
                   4545:   /*
                   4546:    * and after some iteration: */
                   4547:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4548:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4549:   /*  0,                   0                  , 1} */
                   4550:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4551:   /* {0.51571254859325999, 0.4842874514067399, */
                   4552:   /*  0.51326036147820708, 0.48673963852179264} */
                   4553:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  4554:     
1.332     brouard  4555:     int i, ii,j,k, k1;
1.209     brouard  4556:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  4557:   /* double **matprod2(); */ /* test */
1.218     brouard  4558:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  4559:   double **newm;
1.209     brouard  4560:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  4561:   int ncvloop=0;
1.288     brouard  4562:   int first=0;
1.169     brouard  4563:   
1.209     brouard  4564:   min=vector(1,nlstate);
                   4565:   max=vector(1,nlstate);
                   4566:   meandiff=vector(1,nlstate);
                   4567: 
1.218     brouard  4568:        /* Starting with matrix unity */
1.126     brouard  4569:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4570:     for (j=1;j<=nlstate+ndeath;j++){
                   4571:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4572:     }
1.169     brouard  4573:   
                   4574:   cov[1]=1.;
                   4575:   
                   4576:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  4577:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  4578:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  4579:     ncvloop++;
1.126     brouard  4580:     newm=savm;
                   4581:     /* Covariates have to be included here again */
1.138     brouard  4582:     cov[2]=agefin;
1.319     brouard  4583:      if(nagesqr==1){
                   4584:       cov[3]= agefin*agefin;
                   4585:      }
1.332     brouard  4586:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   4587:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   4588:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4589:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4590:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4591:        }else{
                   4592:         cov[2+nagesqr+k1]=precov[nres][k1];
                   4593:        }
                   4594:      }/* End of loop on model equation */
                   4595:      
                   4596: /* Start of old code (replaced by a loop on position in the model equation */
                   4597:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   4598:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4599:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   4600:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   4601:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   4602:     /*    * k                  1        2      3    4      5      6     7        8 */
                   4603:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   4604:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   4605:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   4606:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   4607:     /*    *nsd=3                              (1)  (2)           (3) */
                   4608:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   4609:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   4610:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   4611:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   4612:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   4613:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   4614:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   4615:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   4616:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   4617:     /*    *TvarsDpType */
                   4618:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   4619:     /*    * nsd=1              (1)           (2) */
                   4620:     /*    *TvarsD[nsd]          3             2 */
                   4621:     /*    *TnsdVar           (3)=1          (2)=2 */
                   4622:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   4623:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   4624:     /*    *\/ */
                   4625:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   4626:     /*   /\* 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)); *\/ */
                   4627:     /* } */
                   4628:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   4629:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4630:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   4631:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   4632:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   4633:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4634:     /*   /\* 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]); *\/ */
                   4635:     /* } */
                   4636:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4637:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   4638:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4639:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   4640:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   4641:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4642:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4643:     /*   } */
                   4644:     /*   /\* 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]); *\/ */
                   4645:     /* } */
                   4646:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4647:     /*   /\* 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]); *\/ */
                   4648:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4649:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4650:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4651:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4652:     /*         }else{ */
                   4653:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4654:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   4655:     /*         } */
                   4656:     /*   }else{ */
                   4657:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4658:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4659:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   4660:     /*         }else{ */
                   4661:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4662:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   4663:     /*         } */
                   4664:     /*   } */
                   4665:     /* } /\* End product without age *\/ */
                   4666: /* ENd of old code */
1.138     brouard  4667:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4668:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4669:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  4670:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4671:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  4672:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  4673:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  4674:     
1.126     brouard  4675:     savm=oldm;
                   4676:     oldm=newm;
1.209     brouard  4677: 
                   4678:     for(j=1; j<=nlstate; j++){
                   4679:       max[j]=0.;
                   4680:       min[j]=1.;
                   4681:     }
                   4682:     for(i=1;i<=nlstate;i++){
                   4683:       sumnew=0;
                   4684:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   4685:       for(j=1; j<=nlstate; j++){ 
                   4686:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   4687:        max[j]=FMAX(max[j],prlim[i][j]);
                   4688:        min[j]=FMIN(min[j],prlim[i][j]);
                   4689:       }
                   4690:     }
                   4691: 
1.126     brouard  4692:     maxmax=0.;
1.209     brouard  4693:     for(j=1; j<=nlstate; j++){
                   4694:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   4695:       maxmax=FMAX(maxmax,meandiff[j]);
                   4696:       /* 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  4697:     } /* j loop */
1.203     brouard  4698:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  4699:     /* 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  4700:     if(maxmax < ftolpl){
1.209     brouard  4701:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   4702:       free_vector(min,1,nlstate);
                   4703:       free_vector(max,1,nlstate);
                   4704:       free_vector(meandiff,1,nlstate);
1.126     brouard  4705:       return prlim;
                   4706:     }
1.288     brouard  4707:   } /* agefin loop */
1.208     brouard  4708:     /* After some age loop it doesn't converge */
1.288     brouard  4709:   if(!first){
                   4710:     first=1;
                   4711:     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  4712:     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);
                   4713:   }else if (first >=1 && first <10){
                   4714:     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);
                   4715:     first++;
                   4716:   }else if (first ==10){
                   4717:     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);
                   4718:     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");
                   4719:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   4720:     first++;
1.288     brouard  4721:   }
                   4722: 
1.359     brouard  4723:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl,
                   4724:    * (int)age, (int)delaymax, (int)agefin, ncvloop,
                   4725:    * (int)age-(int)agefin); */
1.209     brouard  4726:   free_vector(min,1,nlstate);
                   4727:   free_vector(max,1,nlstate);
                   4728:   free_vector(meandiff,1,nlstate);
1.208     brouard  4729:   
1.169     brouard  4730:   return prlim; /* should not reach here */
1.126     brouard  4731: }
                   4732: 
1.217     brouard  4733: 
                   4734:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   4735: 
1.218     brouard  4736:  /* 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) */
                   4737:  /* 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  4738:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  4739: {
1.264     brouard  4740:   /* 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  4741:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   4742:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   4743:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   4744:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   4745:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   4746:   /* Initial matrix pimij */
                   4747:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4748:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4749:   /*  0,                   0                  , 1} */
                   4750:   /*
                   4751:    * and after some iteration: */
                   4752:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4753:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4754:   /*  0,                   0                  , 1} */
                   4755:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4756:   /* {0.51571254859325999, 0.4842874514067399, */
                   4757:   /*  0.51326036147820708, 0.48673963852179264} */
                   4758:   /* If we start from prlim again, prlim tends to a constant matrix */
                   4759: 
1.359     brouard  4760:   int i, ii,j, k1;
1.247     brouard  4761:   int first=0;
1.217     brouard  4762:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   4763:   /* double **matprod2(); */ /* test */
                   4764:   double **out, cov[NCOVMAX+1], **bmij();
                   4765:   double **newm;
1.218     brouard  4766:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   4767:   double        **oldm, **savm;  /* for use */
                   4768: 
1.217     brouard  4769:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   4770:   int ncvloop=0;
                   4771:   
                   4772:   min=vector(1,nlstate);
                   4773:   max=vector(1,nlstate);
                   4774:   meandiff=vector(1,nlstate);
                   4775: 
1.266     brouard  4776:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   4777:   oldm=oldms; savm=savms;
                   4778:   
                   4779:   /* Starting with matrix unity */
                   4780:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4781:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  4782:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4783:     }
                   4784:   
                   4785:   cov[1]=1.;
                   4786:   
                   4787:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4788:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  4789:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  4790:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   4791:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  4792:     ncvloop++;
1.218     brouard  4793:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   4794:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  4795:     /* Covariates have to be included here again */
                   4796:     cov[2]=agefin;
1.319     brouard  4797:     if(nagesqr==1){
1.217     brouard  4798:       cov[3]= agefin*agefin;;
1.319     brouard  4799:     }
1.332     brouard  4800:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4801:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4802:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  4803:       }else{
1.332     brouard  4804:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  4805:       }
1.332     brouard  4806:     }/* End of loop on model equation */
                   4807: 
                   4808: /* Old code */ 
                   4809: 
                   4810:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   4811:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4812:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   4813:     /*   /\* 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)); *\/ */
                   4814:     /* } */
                   4815:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   4816:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4817:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4818:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   4819:     /* /\* } *\/ */
                   4820:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4821:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4822:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4823:     /*   /\* 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]); *\/ */
                   4824:     /* } */
                   4825:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   4826:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   4827:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   4828:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4829:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4830:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   4831:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4832:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4833:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4834:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4835:     /*   } */
                   4836:     /*   /\* 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]); *\/ */
                   4837:     /* } */
                   4838:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4839:     /*   /\* 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]); *\/ */
                   4840:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4841:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4842:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4843:     /*         }else{ */
                   4844:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4845:     /*         } */
                   4846:     /*   }else{ */
                   4847:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4848:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4849:     /*         }else{ */
                   4850:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4851:     /*         } */
                   4852:     /*   } */
                   4853:     /* } */
1.217     brouard  4854:     
                   4855:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4856:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4857:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   4858:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4859:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  4860:                /* ij should be linked to the correct index of cov */
                   4861:                /* age and covariate values ij are in 'cov', but we need to pass
                   4862:                 * ij for the observed prevalence at age and status and covariate
                   4863:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   4864:                 */
                   4865:     /* 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 *\/ */
                   4866:     /* 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 *\/ */
                   4867:     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  4868:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  4869:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   4870:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   4871:     /*         printf("%d newm= ",i); */
                   4872:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4873:     /*           printf("%f ",newm[i][j]); */
                   4874:     /*         } */
                   4875:     /*         printf("oldm * "); */
                   4876:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4877:     /*           printf("%f ",oldm[i][j]); */
                   4878:     /*         } */
1.268     brouard  4879:     /*         printf(" bmmij "); */
1.266     brouard  4880:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4881:     /*           printf("%f ",pmmij[i][j]); */
                   4882:     /*         } */
                   4883:     /*         printf("\n"); */
                   4884:     /*   } */
                   4885:     /* } */
1.217     brouard  4886:     savm=oldm;
                   4887:     oldm=newm;
1.266     brouard  4888: 
1.217     brouard  4889:     for(j=1; j<=nlstate; j++){
                   4890:       max[j]=0.;
                   4891:       min[j]=1.;
                   4892:     }
                   4893:     for(j=1; j<=nlstate; j++){ 
                   4894:       for(i=1;i<=nlstate;i++){
1.234     brouard  4895:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   4896:        bprlim[i][j]= newm[i][j];
                   4897:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   4898:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  4899:       }
                   4900:     }
1.218     brouard  4901:                
1.217     brouard  4902:     maxmax=0.;
                   4903:     for(i=1; i<=nlstate; i++){
1.318     brouard  4904:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  4905:       maxmax=FMAX(maxmax,meandiff[i]);
                   4906:       /* 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  4907:     } /* i loop */
1.217     brouard  4908:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  4909:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4910:     if(maxmax < ftolpl){
1.220     brouard  4911:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4912:       free_vector(min,1,nlstate);
                   4913:       free_vector(max,1,nlstate);
                   4914:       free_vector(meandiff,1,nlstate);
                   4915:       return bprlim;
                   4916:     }
1.288     brouard  4917:   } /* agefin loop */
1.217     brouard  4918:     /* After some age loop it doesn't converge */
1.288     brouard  4919:   if(!first){
1.247     brouard  4920:     first=1;
                   4921:     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\
                   4922: 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);
                   4923:   }
                   4924:   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  4925: 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);
                   4926:   /* 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); */
                   4927:   free_vector(min,1,nlstate);
                   4928:   free_vector(max,1,nlstate);
                   4929:   free_vector(meandiff,1,nlstate);
                   4930:   
                   4931:   return bprlim; /* should not reach here */
                   4932: }
                   4933: 
1.126     brouard  4934: /*************** transition probabilities ***************/ 
                   4935: 
                   4936: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   4937: {
1.138     brouard  4938:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  4939:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  4940:      model to the ncovmodel covariates (including constant and age).
                   4941:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   4942:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   4943:      ncth covariate in the global vector x is given by the formula:
                   4944:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   4945:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   4946:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   4947:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  4948:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  4949:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  4950:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  4951:   */
                   4952:   double s1, lnpijopii;
1.126     brouard  4953:   /*double t34;*/
1.164     brouard  4954:   int i,j, nc, ii, jj;
1.126     brouard  4955: 
1.223     brouard  4956:   for(i=1; i<= nlstate; i++){
                   4957:     for(j=1; j<i;j++){
                   4958:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4959:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   4960:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   4961:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   4962:       }
                   4963:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4964:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4965:     }
                   4966:     for(j=i+1; j<=nlstate+ndeath;j++){
                   4967:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4968:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   4969:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   4970:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   4971:       }
                   4972:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4973:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4974:     }
                   4975:   }
1.218     brouard  4976:   
1.223     brouard  4977:   for(i=1; i<= nlstate; i++){
                   4978:     s1=0;
                   4979:     for(j=1; j<i; j++){
1.339     brouard  4980:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  4981:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   4982:     }
                   4983:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  4984:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  4985:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   4986:     }
                   4987:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   4988:     ps[i][i]=1./(s1+1.);
                   4989:     /* Computing other pijs */
                   4990:     for(j=1; j<i; j++)
1.325     brouard  4991:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  4992:     for(j=i+1; j<=nlstate+ndeath; j++)
                   4993:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   4994:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   4995:   } /* end i */
1.218     brouard  4996:   
1.223     brouard  4997:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   4998:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   4999:       ps[ii][jj]=0;
                   5000:       ps[ii][ii]=1;
                   5001:     }
                   5002:   }
1.294     brouard  5003: 
                   5004: 
1.223     brouard  5005:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5006:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5007:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5008:   /*   } */
                   5009:   /*   printf("\n "); */
                   5010:   /* } */
                   5011:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5012:   /*
                   5013:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  5014:                goto end;*/
1.266     brouard  5015:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  5016: }
                   5017: 
1.218     brouard  5018: /*************** backward transition probabilities ***************/ 
                   5019: 
                   5020:  /* 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 ) */
                   5021: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   5022:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   5023: {
1.302     brouard  5024:   /* 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  5025:    * 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  5026:    */
1.359     brouard  5027:   int ii, j;
1.222     brouard  5028:   
1.359     brouard  5029:   double  **pmij();
1.222     brouard  5030:   double sumnew=0.;
1.218     brouard  5031:   double agefin;
1.292     brouard  5032:   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  5033:   double **dnewm, **dsavm, **doldm;
                   5034:   double **bbmij;
                   5035:   
1.218     brouard  5036:   doldm=ddoldms; /* global pointers */
1.222     brouard  5037:   dnewm=ddnewms;
                   5038:   dsavm=ddsavms;
1.318     brouard  5039: 
                   5040:   /* Debug */
                   5041:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  5042:   agefin=cov[2];
1.268     brouard  5043:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  5044:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  5045:      the observed prevalence (with this covariate ij) at beginning of transition */
                   5046:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  5047: 
                   5048:   /* P_x */
1.325     brouard  5049:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  5050:   /* outputs pmmij which is a stochastic matrix in row */
                   5051: 
                   5052:   /* Diag(w_x) */
1.292     brouard  5053:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  5054:   sumnew=0.;
1.269     brouard  5055:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  5056:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  5057:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  5058:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   5059:   }
                   5060:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   5061:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5062:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  5063:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  5064:     }
                   5065:   }else{
                   5066:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5067:       for (j=1;j<=nlstate+ndeath;j++)
                   5068:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   5069:     }
                   5070:     /* if(sumnew <0.9){ */
                   5071:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   5072:     /* } */
                   5073:   }
                   5074:   k3=0.0;  /* We put the last diagonal to 0 */
                   5075:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   5076:       doldm[ii][ii]= k3;
                   5077:   }
                   5078:   /* End doldm, At the end doldm is diag[(w_i)] */
                   5079:   
1.292     brouard  5080:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   5081:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  5082: 
1.292     brouard  5083:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  5084:   /* 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  5085:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  5086:     sumnew=0.;
1.222     brouard  5087:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  5088:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  5089:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  5090:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  5091:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  5092:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  5093:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5094:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  5095:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5096:        /* }else */
1.268     brouard  5097:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   5098:     } /*End ii */
                   5099:   } /* 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 */
                   5100: 
1.292     brouard  5101:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  5102:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  5103:   /* end bmij */
1.266     brouard  5104:   return ps; /*pointer is unchanged */
1.218     brouard  5105: }
1.217     brouard  5106: /*************** transition probabilities ***************/ 
                   5107: 
1.218     brouard  5108: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  5109: {
                   5110:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   5111:      computes the probability to be observed in state j being in state i by appying the
                   5112:      model to the ncovmodel covariates (including constant and age).
                   5113:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   5114:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   5115:      ncth covariate in the global vector x is given by the formula:
                   5116:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   5117:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   5118:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   5119:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   5120:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   5121:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   5122:   */
                   5123:   double s1, lnpijopii;
                   5124:   /*double t34;*/
                   5125:   int i,j, nc, ii, jj;
                   5126: 
1.234     brouard  5127:   for(i=1; i<= nlstate; i++){
                   5128:     for(j=1; j<i;j++){
                   5129:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5130:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   5131:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   5132:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5133:       }
                   5134:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5135:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5136:     }
                   5137:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5138:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5139:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5140:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5141:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5142:       }
                   5143:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5144:     }
                   5145:   }
                   5146:   
                   5147:   for(i=1; i<= nlstate; i++){
                   5148:     s1=0;
                   5149:     for(j=1; j<i; j++){
                   5150:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5151:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5152:     }
                   5153:     for(j=i+1; j<=nlstate+ndeath; j++){
                   5154:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5155:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5156:     }
                   5157:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5158:     ps[i][i]=1./(s1+1.);
                   5159:     /* Computing other pijs */
                   5160:     for(j=1; j<i; j++)
                   5161:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5162:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5163:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5164:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5165:   } /* end i */
                   5166:   
                   5167:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5168:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5169:       ps[ii][jj]=0;
                   5170:       ps[ii][ii]=1;
                   5171:     }
                   5172:   }
1.296     brouard  5173:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  5174:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5175:     s1=0.;
                   5176:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   5177:       s1+=ps[ii][jj];
                   5178:     }
                   5179:     for(ii=1; ii<= nlstate; ii++){
                   5180:       ps[ii][jj]=ps[ii][jj]/s1;
                   5181:     }
                   5182:   }
                   5183:   /* Transposition */
                   5184:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5185:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   5186:       s1=ps[ii][jj];
                   5187:       ps[ii][jj]=ps[jj][ii];
                   5188:       ps[jj][ii]=s1;
                   5189:     }
                   5190:   }
                   5191:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5192:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5193:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5194:   /*   } */
                   5195:   /*   printf("\n "); */
                   5196:   /* } */
                   5197:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5198:   /*
                   5199:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   5200:     goto end;*/
                   5201:   return ps;
1.217     brouard  5202: }
                   5203: 
                   5204: 
1.126     brouard  5205: /**************** Product of 2 matrices ******************/
                   5206: 
1.145     brouard  5207: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  5208: {
                   5209:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   5210:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   5211:   /* in, b, out are matrice of pointers which should have been initialized 
                   5212:      before: only the contents of out is modified. The function returns
                   5213:      a pointer to pointers identical to out */
1.145     brouard  5214:   int i, j, k;
1.126     brouard  5215:   for(i=nrl; i<= nrh; i++)
1.145     brouard  5216:     for(k=ncolol; k<=ncoloh; k++){
                   5217:       out[i][k]=0.;
                   5218:       for(j=ncl; j<=nch; j++)
                   5219:        out[i][k] +=in[i][j]*b[j][k];
                   5220:     }
1.126     brouard  5221:   return out;
                   5222: }
                   5223: 
                   5224: 
                   5225: /************* Higher Matrix Product ***************/
                   5226: 
1.235     brouard  5227: 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  5228: {
1.336     brouard  5229:   /* Already optimized with precov.
                   5230:      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  5231:      'nhstepm*hstepm*stepm' months (i.e. until
                   5232:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   5233:      nhstepm*hstepm matrices. 
                   5234:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   5235:      (typically every 2 years instead of every month which is too big 
                   5236:      for the memory).
                   5237:      Model is determined by parameters x and covariates have to be 
                   5238:      included manually here. 
                   5239: 
                   5240:      */
                   5241: 
1.359     brouard  5242:   int i, j, d, h, k1;
1.131     brouard  5243:   double **out, cov[NCOVMAX+1];
1.126     brouard  5244:   double **newm;
1.187     brouard  5245:   double agexact;
1.359     brouard  5246:   /*double agebegin, ageend;*/
1.126     brouard  5247: 
                   5248:   /* Hstepm could be zero and should return the unit matrix */
                   5249:   for (i=1;i<=nlstate+ndeath;i++)
                   5250:     for (j=1;j<=nlstate+ndeath;j++){
                   5251:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5252:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5253:     }
                   5254:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5255:   for(h=1; h <=nhstepm; h++){
                   5256:     for(d=1; d <=hstepm; d++){
                   5257:       newm=savm;
                   5258:       /* Covariates have to be included here again */
                   5259:       cov[1]=1.;
1.214     brouard  5260:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  5261:       cov[2]=agexact;
1.319     brouard  5262:       if(nagesqr==1){
1.227     brouard  5263:        cov[3]= agexact*agexact;
1.319     brouard  5264:       }
1.330     brouard  5265:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   5266:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   5267:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5268:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5269:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   5270:        }else{
                   5271:          cov[2+nagesqr+k1]=precov[nres][k1];
                   5272:        }
                   5273:       }/* End of loop on model equation */
                   5274:        /* Old code */ 
                   5275: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   5276: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   5277: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   5278: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   5279: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   5280: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5281: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5282: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   5283: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   5284: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   5285: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   5286: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   5287: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   5288: /*       /\* 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]])); *\/ */
                   5289: /*       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); */
                   5290: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5291: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   5292: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   5293: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   5294: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   5295: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   5296: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   5297: /*       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]]); */
                   5298: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5299: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   5300: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   5301: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   5302: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   5303: /*       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]); */
                   5304: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5305: 
                   5306: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   5307: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   5308: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   5309: /*       /\* *\/ */
1.330     brouard  5310: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5311: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5312: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  5313: /* /\*cptcovage=2                   1               2      *\/ */
                   5314: /* /\*Tage[k]=                      5               8      *\/  */
                   5315: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   5316: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   5317: /*       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]]); */
                   5318: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5319: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   5320: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   5321: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   5322: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   5323: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   5324: /*       /\*   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); *\/ */
                   5325: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   5326: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   5327: /*       /\* } *\/ */
                   5328: /*       /\* 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]); *\/ */
                   5329: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   5330: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   5331: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   5332: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   5333: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   5334: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   5335: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   5336: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   5337: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  5338:          
1.332     brouard  5339: /*       /\* 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])]); *\/ */
                   5340: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5341: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   5342: /*       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]]); */
                   5343: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5344: 
                   5345: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   5346: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   5347: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5348: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   5349: /*           /\* 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]])]; *\/ */
                   5350: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   5351: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   5352: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   5353: /*       /\*   } *\/ */
                   5354: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   5355: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   5356: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   5357: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5358: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   5359: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   5360: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5361: /*       /\*   } *\/ */
                   5362: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   5363: /*     }/\*end of products *\/ */
                   5364:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  5365:       /* for (k=1; k<=cptcovn;k++)  */
                   5366:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   5367:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   5368:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   5369:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   5370:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  5371:       
                   5372:       
1.126     brouard  5373:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   5374:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  5375:       /* right multiplication of oldm by the current matrix */
1.126     brouard  5376:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   5377:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  5378:       /* if((int)age == 70){ */
                   5379:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5380:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5381:       /*         printf("%d pmmij ",i); */
                   5382:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5383:       /*           printf("%f ",pmmij[i][j]); */
                   5384:       /*         } */
                   5385:       /*         printf(" oldm "); */
                   5386:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5387:       /*           printf("%f ",oldm[i][j]); */
                   5388:       /*         } */
                   5389:       /*         printf("\n"); */
                   5390:       /*       } */
                   5391:       /* } */
1.126     brouard  5392:       savm=oldm;
                   5393:       oldm=newm;
                   5394:     }
                   5395:     for(i=1; i<=nlstate+ndeath; i++)
                   5396:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  5397:        po[i][j][h]=newm[i][j];
                   5398:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  5399:       }
1.128     brouard  5400:     /*printf("h=%d ",h);*/
1.126     brouard  5401:   } /* end h */
1.267     brouard  5402:   /*     printf("\n H=%d \n",h); */
1.126     brouard  5403:   return po;
                   5404: }
                   5405: 
1.217     brouard  5406: /************* Higher Back Matrix Product ***************/
1.218     brouard  5407: /* 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  5408: 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  5409: {
1.332     brouard  5410:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   5411:      computes the transition matrix starting at age 'age' over
1.217     brouard  5412:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  5413:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   5414:      nhstepm*hstepm matrices.
                   5415:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   5416:      (typically every 2 years instead of every month which is too big
1.217     brouard  5417:      for the memory).
1.218     brouard  5418:      Model is determined by parameters x and covariates have to be
1.266     brouard  5419:      included manually here. Then we use a call to bmij(x and cov)
                   5420:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  5421:   */
1.217     brouard  5422: 
1.359     brouard  5423:   int i, j, d, h, k1;
1.266     brouard  5424:   double **out, cov[NCOVMAX+1], **bmij();
                   5425:   double **newm, ***newmm;
1.217     brouard  5426:   double agexact;
1.359     brouard  5427:   /*double agebegin, ageend;*/
1.222     brouard  5428:   double **oldm, **savm;
1.217     brouard  5429: 
1.266     brouard  5430:   newmm=po; /* To be saved */
                   5431:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  5432:   /* Hstepm could be zero and should return the unit matrix */
                   5433:   for (i=1;i<=nlstate+ndeath;i++)
                   5434:     for (j=1;j<=nlstate+ndeath;j++){
                   5435:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5436:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5437:     }
                   5438:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5439:   for(h=1; h <=nhstepm; h++){
                   5440:     for(d=1; d <=hstepm; d++){
                   5441:       newm=savm;
                   5442:       /* Covariates have to be included here again */
                   5443:       cov[1]=1.;
1.271     brouard  5444:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  5445:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  5446:         /* Debug */
                   5447:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  5448:       cov[2]=agexact;
1.332     brouard  5449:       if(nagesqr==1){
1.222     brouard  5450:        cov[3]= agexact*agexact;
1.332     brouard  5451:       }
                   5452:       /** New code */
                   5453:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5454:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5455:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  5456:        }else{
1.332     brouard  5457:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  5458:        }
1.332     brouard  5459:       }/* End of loop on model equation */
                   5460:       /** End of new code */
                   5461:   /** This was old code */
                   5462:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   5463:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   5464:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   5465:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   5466:       /*   /\* 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)); *\/ */
                   5467:       /* } */
                   5468:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   5469:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   5470:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   5471:       /*       /\* 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]); *\/ */
                   5472:       /* } */
                   5473:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   5474:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   5475:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   5476:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   5477:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   5478:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   5479:       /*       } */
                   5480:       /*       /\* 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]); *\/ */
                   5481:       /* } */
                   5482:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   5483:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   5484:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   5485:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5486:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   5487:       /*         }else{ */
                   5488:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   5489:       /*         } */
                   5490:       /*       }else{ */
                   5491:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5492:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   5493:       /*         }else{ */
                   5494:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   5495:       /*         } */
                   5496:       /*       } */
                   5497:       /* }                      */
                   5498:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   5499:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   5500: /** End of old code */
                   5501:       
1.218     brouard  5502:       /* Careful transposed matrix */
1.266     brouard  5503:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  5504:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  5505:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  5506:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  5507:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  5508:       /* if((int)age == 70){ */
                   5509:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5510:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5511:       /*         printf("%d pmmij ",i); */
                   5512:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5513:       /*           printf("%f ",pmmij[i][j]); */
                   5514:       /*         } */
                   5515:       /*         printf(" oldm "); */
                   5516:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5517:       /*           printf("%f ",oldm[i][j]); */
                   5518:       /*         } */
                   5519:       /*         printf("\n"); */
                   5520:       /*       } */
                   5521:       /* } */
                   5522:       savm=oldm;
                   5523:       oldm=newm;
                   5524:     }
                   5525:     for(i=1; i<=nlstate+ndeath; i++)
                   5526:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  5527:        po[i][j][h]=newm[i][j];
1.268     brouard  5528:        /* if(h==nhstepm) */
                   5529:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  5530:       }
1.268     brouard  5531:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  5532:   } /* end h */
1.268     brouard  5533:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  5534:   return po;
                   5535: }
                   5536: 
                   5537: 
1.162     brouard  5538: #ifdef NLOPT
                   5539:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   5540:   double fret;
                   5541:   double *xt;
                   5542:   int j;
                   5543:   myfunc_data *d2 = (myfunc_data *) pd;
                   5544: /* xt = (p1-1); */
                   5545:   xt=vector(1,n); 
                   5546:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   5547: 
                   5548:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   5549:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   5550:   printf("Function = %.12lf ",fret);
                   5551:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   5552:   printf("\n");
                   5553:  free_vector(xt,1,n);
                   5554:   return fret;
                   5555: }
                   5556: #endif
1.126     brouard  5557: 
                   5558: /*************** log-likelihood *************/
                   5559: double func( double *x)
                   5560: {
1.336     brouard  5561:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  5562:   int ioffset=0;
1.339     brouard  5563:   int ipos=0,iposold=0,ncovv=0;
                   5564: 
1.340     brouard  5565:   double cotvarv, cotvarvold;
1.226     brouard  5566:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   5567:   double **out;
                   5568:   double lli; /* Individual log likelihood */
                   5569:   int s1, s2;
1.228     brouard  5570:   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  5571: 
1.226     brouard  5572:   double bbh, survp;
                   5573:   double agexact;
1.336     brouard  5574:   double agebegin, ageend;
1.226     brouard  5575:   /*extern weight */
                   5576:   /* We are differentiating ll according to initial status */
                   5577:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5578:   /*for(i=1;i<imx;i++) 
                   5579:     printf(" %d\n",s[4][i]);
                   5580:   */
1.162     brouard  5581: 
1.226     brouard  5582:   ++countcallfunc;
1.162     brouard  5583: 
1.226     brouard  5584:   cov[1]=1.;
1.126     brouard  5585: 
1.226     brouard  5586:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5587:   ioffset=0;
1.226     brouard  5588:   if(mle==1){
                   5589:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5590:       /* Computes the values of the ncovmodel covariates of the model
                   5591:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5592:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5593:         to be observed in j being in i according to the model.
                   5594:       */
1.243     brouard  5595:       ioffset=2+nagesqr ;
1.233     brouard  5596:    /* Fixed */
1.345     brouard  5597:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  5598:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   5599:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   5600:        /*  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  5601:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  5602:        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  5603:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  5604:       }
1.226     brouard  5605:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  5606:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  5607:         has been calculated etc */
                   5608:       /* For an individual i, wav[i] gives the number of effective waves */
                   5609:       /* We compute the contribution to Likelihood of each effective transition
                   5610:         mw[mi][i] is real wave of the mi th effectve wave */
                   5611:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   5612:         s2=s[mw[mi+1][i]][i];
1.341     brouard  5613:         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  5614:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   5615:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   5616:       */
1.336     brouard  5617:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   5618:       /* Wave varying (but not age varying) */
1.339     brouard  5619:        /* 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*\/ */
                   5620:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   5621:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   5622:        /* } */
1.340     brouard  5623:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   5624:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5625:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  5626:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  5627:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  5628:          }else{ /* fixed covariate */
1.345     brouard  5629:            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  5630:          }
1.339     brouard  5631:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  5632:            cotvarvold=cotvarv;
                   5633:          }else{ /* A second product */
                   5634:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  5635:          }
                   5636:          iposold=ipos;
1.340     brouard  5637:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  5638:        }
1.339     brouard  5639:        /* for products of time varying to be done */
1.234     brouard  5640:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5641:          for (j=1;j<=nlstate+ndeath;j++){
                   5642:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5643:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5644:          }
1.336     brouard  5645: 
                   5646:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   5647:        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  5648:        for(d=0; d<dh[mi][i]; d++){
                   5649:          newm=savm;
                   5650:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5651:          cov[2]=agexact;
                   5652:          if(nagesqr==1)
                   5653:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  5654:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   5655:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   5656:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   5657:          /*   else */
                   5658:          /*     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) *\/  */
                   5659:          /* } */
                   5660:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5661:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5662:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5663:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5664:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5665:            }else{ /* fixed covariate */
                   5666:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5667:            }
                   5668:            if(ipos!=iposold){ /* Not a product or first of a product */
                   5669:              cotvarvold=cotvarv;
                   5670:            }else{ /* A second product */
                   5671:              cotvarv=cotvarv*cotvarvold;
                   5672:            }
                   5673:            iposold=ipos;
                   5674:            cov[ioffset+ipos]=cotvarv*agexact;
                   5675:            /* For products */
1.234     brouard  5676:          }
1.349     brouard  5677:          
1.234     brouard  5678:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5679:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5680:          savm=oldm;
                   5681:          oldm=newm;
                   5682:        } /* end mult */
                   5683:        
                   5684:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   5685:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   5686:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   5687:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   5688:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   5689:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   5690:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   5691:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  5692:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   5693:                                 * -stepm/2 to stepm/2 .
                   5694:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   5695:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   5696:                                 */
1.234     brouard  5697:        s1=s[mw[mi][i]][i];
                   5698:        s2=s[mw[mi+1][i]][i];
                   5699:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5700:        /* bias bh is positive if real duration
                   5701:         * is higher than the multiple of stepm and negative otherwise.
                   5702:         */
                   5703:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   5704:        if( s2 > nlstate){ 
                   5705:          /* i.e. if s2 is a death state and if the date of death is known 
                   5706:             then the contribution to the likelihood is the probability to 
                   5707:             die between last step unit time and current  step unit time, 
                   5708:             which is also equal to probability to die before dh 
                   5709:             minus probability to die before dh-stepm . 
                   5710:             In version up to 0.92 likelihood was computed
                   5711:             as if date of death was unknown. Death was treated as any other
                   5712:             health state: the date of the interview describes the actual state
                   5713:             and not the date of a change in health state. The former idea was
                   5714:             to consider that at each interview the state was recorded
                   5715:             (healthy, disable or death) and IMaCh was corrected; but when we
                   5716:             introduced the exact date of death then we should have modified
                   5717:             the contribution of an exact death to the likelihood. This new
                   5718:             contribution is smaller and very dependent of the step unit
                   5719:             stepm. It is no more the probability to die between last interview
                   5720:             and month of death but the probability to survive from last
                   5721:             interview up to one month before death multiplied by the
                   5722:             probability to die within a month. Thanks to Chris
                   5723:             Jackson for correcting this bug.  Former versions increased
                   5724:             mortality artificially. The bad side is that we add another loop
                   5725:             which slows down the processing. The difference can be up to 10%
                   5726:             lower mortality.
                   5727:          */
                   5728:          /* If, at the beginning of the maximization mostly, the
                   5729:             cumulative probability or probability to be dead is
                   5730:             constant (ie = 1) over time d, the difference is equal to
                   5731:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   5732:             s1 at precedent wave, to be dead a month before current
                   5733:             wave is equal to probability, being at state s1 at
                   5734:             precedent wave, to be dead at mont of the current
                   5735:             wave. Then the observed probability (that this person died)
                   5736:             is null according to current estimated parameter. In fact,
                   5737:             it should be very low but not zero otherwise the log go to
                   5738:             infinity.
                   5739:          */
1.183     brouard  5740: /* #ifdef INFINITYORIGINAL */
                   5741: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5742: /* #else */
                   5743: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   5744: /*         lli=log(mytinydouble); */
                   5745: /*       else */
                   5746: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5747: /* #endif */
1.226     brouard  5748:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  5749:          
1.226     brouard  5750:        } else if  ( s2==-1 ) { /* alive */
                   5751:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5752:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   5753:          /*survp += out[s1][j]; */
                   5754:          lli= log(survp);
                   5755:        }
1.336     brouard  5756:        /* else if  (s2==-4) {  */
                   5757:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   5758:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5759:        /*   lli= log(survp);  */
                   5760:        /* }  */
                   5761:        /* else if  (s2==-5) {  */
                   5762:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   5763:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5764:        /*   lli= log(survp);  */
                   5765:        /* }  */
1.226     brouard  5766:        else{
                   5767:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5768:          /*  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 */
                   5769:        } 
                   5770:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   5771:        /*if(lli ==000.0)*/
1.340     brouard  5772:        /* 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  5773:        ipmx +=1;
                   5774:        sw += weight[i];
                   5775:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5776:        /* if (lli < log(mytinydouble)){ */
                   5777:        /*   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); */
                   5778:        /*   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]); */
                   5779:        /* } */
                   5780:       } /* end of wave */
                   5781:     } /* end of individual */
                   5782:   }  else if(mle==2){
                   5783:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  5784:       ioffset=2+nagesqr ;
                   5785:       for (k=1; k<=ncovf;k++)
                   5786:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  5787:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  5788:        for(k=1; k <= ncovv ; k++){
1.341     brouard  5789:          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  5790:        }
1.226     brouard  5791:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5792:          for (j=1;j<=nlstate+ndeath;j++){
                   5793:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5794:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5795:          }
                   5796:        for(d=0; d<=dh[mi][i]; d++){
                   5797:          newm=savm;
                   5798:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5799:          cov[2]=agexact;
                   5800:          if(nagesqr==1)
                   5801:            cov[3]= agexact*agexact;
                   5802:          for (kk=1; kk<=cptcovage;kk++) {
                   5803:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5804:          }
                   5805:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5806:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5807:          savm=oldm;
                   5808:          oldm=newm;
                   5809:        } /* end mult */
                   5810:       
                   5811:        s1=s[mw[mi][i]][i];
                   5812:        s2=s[mw[mi+1][i]][i];
                   5813:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5814:        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 */
                   5815:        ipmx +=1;
                   5816:        sw += weight[i];
                   5817:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5818:       } /* end of wave */
                   5819:     } /* end of individual */
                   5820:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   5821:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5822:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5823:       for(mi=1; mi<= wav[i]-1; mi++){
                   5824:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5825:          for (j=1;j<=nlstate+ndeath;j++){
                   5826:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5827:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5828:          }
                   5829:        for(d=0; d<dh[mi][i]; d++){
                   5830:          newm=savm;
                   5831:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5832:          cov[2]=agexact;
                   5833:          if(nagesqr==1)
                   5834:            cov[3]= agexact*agexact;
                   5835:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5836:            if(!FixedV[Tvar[Tage[kk]]])
                   5837:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5838:            else
1.341     brouard  5839:              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  5840:          }
                   5841:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5842:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5843:          savm=oldm;
                   5844:          oldm=newm;
                   5845:        } /* end mult */
                   5846:       
                   5847:        s1=s[mw[mi][i]][i];
                   5848:        s2=s[mw[mi+1][i]][i];
                   5849:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5850:        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 */
                   5851:        ipmx +=1;
                   5852:        sw += weight[i];
                   5853:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5854:       } /* end of wave */
                   5855:     } /* end of individual */
                   5856:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   5857:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5858:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5859:       for(mi=1; mi<= wav[i]-1; mi++){
                   5860:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5861:          for (j=1;j<=nlstate+ndeath;j++){
                   5862:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5863:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5864:          }
                   5865:        for(d=0; d<dh[mi][i]; d++){
                   5866:          newm=savm;
                   5867:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5868:          cov[2]=agexact;
                   5869:          if(nagesqr==1)
                   5870:            cov[3]= agexact*agexact;
                   5871:          for (kk=1; kk<=cptcovage;kk++) {
                   5872:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5873:          }
1.126     brouard  5874:        
1.226     brouard  5875:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5876:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5877:          savm=oldm;
                   5878:          oldm=newm;
                   5879:        } /* end mult */
                   5880:       
                   5881:        s1=s[mw[mi][i]][i];
                   5882:        s2=s[mw[mi+1][i]][i];
                   5883:        if( s2 > nlstate){ 
                   5884:          lli=log(out[s1][s2] - savm[s1][s2]);
                   5885:        } else if  ( s2==-1 ) { /* alive */
                   5886:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5887:            survp += out[s1][j];
                   5888:          lli= log(survp);
                   5889:        }else{
                   5890:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5891:        }
                   5892:        ipmx +=1;
                   5893:        sw += weight[i];
                   5894:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  5895:        /* 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  5896:       } /* end of wave */
                   5897:     } /* end of individual */
                   5898:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   5899:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5900:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5901:       for(mi=1; mi<= wav[i]-1; mi++){
                   5902:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5903:          for (j=1;j<=nlstate+ndeath;j++){
                   5904:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5905:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5906:          }
                   5907:        for(d=0; d<dh[mi][i]; d++){
                   5908:          newm=savm;
                   5909:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5910:          cov[2]=agexact;
                   5911:          if(nagesqr==1)
                   5912:            cov[3]= agexact*agexact;
                   5913:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5914:            if(!FixedV[Tvar[Tage[kk]]])
                   5915:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5916:            else
1.341     brouard  5917:              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  5918:          }
1.126     brouard  5919:        
1.226     brouard  5920:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5921:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5922:          savm=oldm;
                   5923:          oldm=newm;
                   5924:        } /* end mult */
                   5925:       
                   5926:        s1=s[mw[mi][i]][i];
                   5927:        s2=s[mw[mi+1][i]][i];
                   5928:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5929:        ipmx +=1;
                   5930:        sw += weight[i];
                   5931:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5932:        /*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]);*/
                   5933:       } /* end of wave */
                   5934:     } /* end of individual */
                   5935:   } /* End of if */
                   5936:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5937:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5938:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5939:   return -l;
1.126     brouard  5940: }
                   5941: 
                   5942: /*************** log-likelihood *************/
                   5943: double funcone( double *x)
                   5944: {
1.228     brouard  5945:   /* Same as func but slower because of a lot of printf and if */
1.359     brouard  5946:   int i, ii, j, k, mi, d, kv=0, kf=0;
1.228     brouard  5947:   int ioffset=0;
1.339     brouard  5948:   int ipos=0,iposold=0,ncovv=0;
                   5949: 
1.340     brouard  5950:   double cotvarv, cotvarvold;
1.131     brouard  5951:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  5952:   double **out;
                   5953:   double lli; /* Individual log likelihood */
                   5954:   double llt;
                   5955:   int s1, s2;
1.228     brouard  5956:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   5957: 
1.126     brouard  5958:   double bbh, survp;
1.187     brouard  5959:   double agexact;
1.214     brouard  5960:   double agebegin, ageend;
1.126     brouard  5961:   /*extern weight */
                   5962:   /* We are differentiating ll according to initial status */
                   5963:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5964:   /*for(i=1;i<imx;i++) 
                   5965:     printf(" %d\n",s[4][i]);
                   5966:   */
                   5967:   cov[1]=1.;
                   5968: 
                   5969:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5970:   ioffset=0;
                   5971:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  5972:     /* Computes the values of the ncovmodel covariates of the model
                   5973:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5974:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5975:        to be observed in j being in i according to the model.
                   5976:     */
1.243     brouard  5977:     /* ioffset=2+nagesqr+cptcovage; */
                   5978:     ioffset=2+nagesqr;
1.232     brouard  5979:     /* Fixed */
1.224     brouard  5980:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  5981:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  5982:     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  5983:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   5984:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   5985:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  5986:       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  5987: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   5988: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   5989: /*    cov[2+6]=covar[2][i]; V2  */
                   5990: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   5991: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   5992: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   5993: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   5994: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   5995: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  5996:     }
1.336     brouard  5997:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   5998:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   5999:         has been calculated etc */
                   6000:       /* For an individual i, wav[i] gives the number of effective waves */
                   6001:       /* We compute the contribution to Likelihood of each effective transition
                   6002:         mw[mi][i] is real wave of the mi th effectve wave */
                   6003:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   6004:         s2=s[mw[mi+1][i]][i];
1.341     brouard  6005:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  6006:       */
                   6007:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  6008:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   6009:     /*   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?)*\/ */
                   6010:     /* } */
1.231     brouard  6011:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   6012:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   6013:     /* } */
1.225     brouard  6014:     
1.233     brouard  6015: 
                   6016:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  6017:       /* 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 */
                   6018:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   6019:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   6020:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   6021:       /* } */
                   6022:       
                   6023:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   6024:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   6025:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   6026:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   6027:       /* We need the position of the time varying or product in the model */
                   6028:       /* 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 */            
                   6029:       /* TvarVV gives the variable name */
1.340     brouard  6030:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   6031:       *      k=         1   2     3     4         5        6        7       8        9
                   6032:       *  varying            1     2                                 3       4        5
                   6033:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  6034:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  6035:       * TvarVVind           2     3                                7 7     8 8      9 9
                   6036:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   6037:       */
1.345     brouard  6038:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  6039:        * 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  6040:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  6041:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   6042:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   6043:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   6044:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6045:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6046:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6047:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6048:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6049:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6050:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6051:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6052:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6053:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   6054:        *                  12       13      14      15       16
                   6055:        *                    17        18         19        20         21
                   6056:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   6057:        *                   2       3        4       6        7
                   6058:        *                     9         11          12        13         14            
                   6059:        * cptcovage=5+5 total of covariates with age 
                   6060:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   6061:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   6062:        *3 Tage[cptcovage] age*V3*V2=6  
                   6063:        *3                age*V2=12         13      14      15       16
                   6064:        *3                age*V6*V3=18      19    20   21
                   6065:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   6066:        *     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
                   6067:        * 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
                   6068:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   6069:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6070:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   6071:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   6072:        * 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
                   6073:        * Tvar=                {2, 3, 4, 6, 7,
                   6074:        *                       9, 10, 11, 12, 13, 14,
                   6075:        *              Tvar[12]=2, 3, 4, 6, 7,
                   6076:        *              Tvar[17]=9, 11, 12, 13, 14}
                   6077:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   6078:        *                  2, 2, 2, 2, 2, 2,
                   6079:        * 3                3, 2, 2, 2, 2, 2,
                   6080:        *                  1, 1, 1, 1, 1, 
                   6081:        *                  3, 3, 3, 3, 3}
                   6082:        * 3                 2, 3, 3, 3, 3}
                   6083:        * 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
                   6084:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6085:        * 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}
                   6086:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6087:        * cptcovprod=11 (6+5)
                   6088:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   6089:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   6090:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   6091:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   6092:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6093:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6094:        * cptcovdageprod=5  for gnuplot printing
                   6095:        * cptcovprodvage=6 
                   6096:        * ncova=15           1        2       3       4       5
                   6097:        *                      6 7        8 9      10 11        12 13     14 15
                   6098:        * TvarA              2        3       4       6       7
                   6099:        *                      6 2        6 7       7 3          6 4       7 4
                   6100:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  6101:        * ncovf            1     2      3
1.349     brouard  6102:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6103:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   6104:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6105:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   6106:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6107:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6108:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   6109:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   6110:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   6111:        * 3 cptcovprodvage=6
                   6112:        * 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
                   6113:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   6114:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  6115:        *?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  6116:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   6117:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6118:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   6119:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   6120:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   6121:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   6122:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   6123:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  6124:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  6125:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   6126:        *                   2, 3, 4, 6, 7,
                   6127:        *                     6, 8, 9, 10, 11}
1.345     brouard  6128:        * TvarFind[itv]                        0      0       0
                   6129:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  6130:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  6131:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   6132:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   6133:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  6134:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  6135:        */
                   6136: 
1.349     brouard  6137:       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 */
                   6138:        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  6139:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  6140:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6141:        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  6142:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  6143:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  6144:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6145:        }else{ /* fixed covariate */
1.345     brouard  6146:          /* 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  6147:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  6148:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  6149:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6150:        }
1.339     brouard  6151:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  6152:          cotvarvold=cotvarv;
                   6153:        }else{ /* A second product */
                   6154:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  6155:        }
                   6156:        iposold=ipos;
1.340     brouard  6157:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  6158:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  6159:        /* For products */
                   6160:       }
                   6161:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   6162:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   6163:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   6164:       /*       /\*           1  2   3      4      5                         *\/ */
                   6165:       /*       /\*itv           1                                           *\/ */
                   6166:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   6167:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   6168:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   6169:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   6170:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   6171:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   6172:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   6173:       /*       /\* 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]); *\/ */
                   6174:       /* } */
1.232     brouard  6175:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  6176:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   6177:       /*       /\* 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]); *\/ */
                   6178:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  6179:       /* } */
1.126     brouard  6180:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  6181:        for (j=1;j<=nlstate+ndeath;j++){
                   6182:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6183:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6184:        }
1.214     brouard  6185:       
                   6186:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   6187:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   6188:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  6189:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  6190:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6191:          and mw[mi+1][i]. dh depends on stepm.*/
                   6192:        newm=savm;
1.247     brouard  6193:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  6194:        cov[2]=agexact;
                   6195:        if(nagesqr==1)
                   6196:          cov[3]= agexact*agexact;
1.349     brouard  6197:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6198:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6199:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6200:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6201:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6202:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6203:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6204:          }else{ /* fixed covariate */
                   6205:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6206:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6207:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6208:          }
                   6209:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6210:            cotvarvold=cotvarv;
                   6211:          }else{ /* A second product */
                   6212:            /* printf("DEBUG * \n"); */
                   6213:            cotvarv=cotvarv*cotvarvold;
                   6214:          }
                   6215:          iposold=ipos;
                   6216:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6217:          cov[ioffset+ipos]=cotvarv*agexact;
                   6218:          /* For products */
1.242     brouard  6219:        }
1.349     brouard  6220: 
1.242     brouard  6221:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   6222:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   6223:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   6224:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   6225:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   6226:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   6227:        savm=oldm;
                   6228:        oldm=newm;
1.126     brouard  6229:       } /* end mult */
1.336     brouard  6230:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   6231:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   6232:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   6233:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   6234:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   6235:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   6236:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   6237:         * probability in order to take into account the bias as a fraction of the way
                   6238:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   6239:                                 * -stepm/2 to stepm/2 .
                   6240:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   6241:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   6242:                                 */
1.126     brouard  6243:       s1=s[mw[mi][i]][i];
                   6244:       s2=s[mw[mi+1][i]][i];
1.217     brouard  6245:       /* if(s2==-1){ */
1.268     brouard  6246:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  6247:       /*       /\* exit(1); *\/ */
                   6248:       /* } */
1.126     brouard  6249:       bbh=(double)bh[mi][i]/(double)stepm; 
                   6250:       /* bias is positive if real duration
                   6251:        * is higher than the multiple of stepm and negative otherwise.
                   6252:        */
                   6253:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  6254:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  6255:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  6256:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   6257:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   6258:        lli= log(survp);
1.126     brouard  6259:       }else if (mle==1){
1.242     brouard  6260:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  6261:       } else if(mle==2){
1.242     brouard  6262:        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  6263:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  6264:        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  6265:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  6266:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  6267:       } else{  /* mle=0 back to 1 */
1.242     brouard  6268:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   6269:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  6270:       } /* End of if */
                   6271:       ipmx +=1;
                   6272:       sw += weight[i];
                   6273:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  6274:       /* Printing covariates values for each contribution for checking */
1.343     brouard  6275:       /* 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  6276:       if(globpr){
1.246     brouard  6277:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  6278:  %11.6f %11.6f %11.6f ", \
1.242     brouard  6279:                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  6280:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  6281:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   6282:        /* %11.6f %11.6f %11.6f ", \ */
                   6283:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   6284:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  6285:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   6286:          llt +=ll[k]*gipmx/gsw;
                   6287:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  6288:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  6289:        }
1.343     brouard  6290:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  6291:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  6292:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  6293:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   6294:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   6295:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   6296:        }
                   6297:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   6298:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6299:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6300:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   6301:            /* printf(" %g",cov[ioffset+ipos]); */
                   6302:          }else{
                   6303:            fprintf(ficresilk,"*");
                   6304:            /* printf("*"); */
1.342     brouard  6305:          }
1.343     brouard  6306:          iposold=ipos;
                   6307:        }
1.349     brouard  6308:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   6309:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   6310:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   6311:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   6312:        /*   }else{ */
                   6313:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6314:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   6315:        /*   } */
                   6316:        /* } */
                   6317:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6318:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6319:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6320:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6321:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6322:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6323:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6324:          }else{ /* fixed covariate */
                   6325:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6326:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6327:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6328:          }
                   6329:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6330:            cotvarvold=cotvarv;
                   6331:          }else{ /* A second product */
                   6332:            /* printf("DEBUG * \n"); */
                   6333:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  6334:          }
1.349     brouard  6335:          cotvarv=cotvarv*agexact;
                   6336:          fprintf(ficresilk," %g*age",cotvarv);
                   6337:          iposold=ipos;
                   6338:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6339:          cov[ioffset+ipos]=cotvarv;
                   6340:          /* For products */
1.343     brouard  6341:        }
                   6342:        /* printf("\n"); */
1.342     brouard  6343:        /* } /\*  End debugILK *\/ */
                   6344:        fprintf(ficresilk,"\n");
                   6345:       } /* End if globpr */
1.335     brouard  6346:     } /* end of wave */
                   6347:   } /* end of individual */
                   6348:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  6349: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  6350:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   6351:   if(globpr==0){ /* First time we count the contributions and weights */
                   6352:     gipmx=ipmx;
                   6353:     gsw=sw;
                   6354:   }
1.343     brouard  6355:   return -l;
1.126     brouard  6356: }
                   6357: 
                   6358: 
                   6359: /*************** function likelione ***********/
1.292     brouard  6360: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  6361: {
                   6362:   /* This routine should help understanding what is done with 
                   6363:      the selection of individuals/waves and
                   6364:      to check the exact contribution to the likelihood.
                   6365:      Plotting could be done.
1.342     brouard  6366:   */
                   6367:   void pstamp(FILE *ficres);
1.343     brouard  6368:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  6369: 
                   6370:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  6371:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  6372:     strcat(fileresilk,fileresu);
1.126     brouard  6373:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   6374:       printf("Problem with resultfile: %s\n", fileresilk);
                   6375:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   6376:     }
1.342     brouard  6377:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  6378:     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");
                   6379:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  6380:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   6381:     for(k=1; k<=nlstate; k++) 
                   6382:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  6383:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   6384: 
                   6385:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   6386:       for(kf=1;kf <= ncovf; kf++){
                   6387:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   6388:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   6389:       }
                   6390:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  6391:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  6392:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6393:          /* printf(" %d",ipos); */
                   6394:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   6395:        }else{
                   6396:          /* printf("*"); */
                   6397:          fprintf(ficresilk,"*");
1.343     brouard  6398:        }
1.342     brouard  6399:        iposold=ipos;
                   6400:       }
                   6401:       for (kk=1; kk<=cptcovage;kk++) {
                   6402:        if(!FixedV[Tvar[Tage[kk]]]){
                   6403:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   6404:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   6405:        }else{
                   6406:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6407:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6408:        }
                   6409:       }
                   6410:     /* } /\* End if debugILK *\/ */
                   6411:     /* printf("\n"); */
                   6412:     fprintf(ficresilk,"\n");
                   6413:   } /* End glogpri */
1.126     brouard  6414: 
1.292     brouard  6415:   *fretone=(*func)(p);
1.126     brouard  6416:   if(*globpri !=0){
                   6417:     fclose(ficresilk);
1.205     brouard  6418:     if (mle ==0)
                   6419:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   6420:     else if(mle >=1)
                   6421:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   6422:     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  6423:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  6424:       
1.207     brouard  6425:     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  6426: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  6427:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  6428: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   6429:     
                   6430:     for (k=1; k<= nlstate ; k++) {
                   6431:       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 \
                   6432: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   6433:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  6434:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   6435:         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]]);
                   6436:         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);
                   6437:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  6438:       }
                   6439:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   6440:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   6441:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   6442:        /* 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]); */
                   6443:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6444:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   6445:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   6446:          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)  */
                   6447:            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> \
                   6448: <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);
                   6449:          } /* End only for dummies time varying (single?) */
                   6450:        }else{ /* Useless product */
                   6451:          /* printf("*"); */
                   6452:          /* fprintf(ficresilk,"*"); */ 
                   6453:        }
                   6454:        iposold=ipos;
                   6455:       } /* For each time varying covariate */
                   6456:     } /* End loop on states */
                   6457: 
                   6458: /*     if(debugILK){ */
                   6459: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   6460: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   6461: /*     for (k=1; k<= nlstate ; k++) { */
                   6462: /*       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> \ */
                   6463: /* <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]]); */
                   6464: /*     } */
                   6465: /*       } */
                   6466: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   6467: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   6468: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   6469: /*     /\* 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]); *\/ */
                   6470: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   6471: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   6472: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   6473: /*       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)  *\/ */
                   6474: /*         for (k=1; k<= nlstate ; k++) { */
                   6475: /*           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> \ */
                   6476: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   6477: /*         } /\* End state *\/ */
                   6478: /*       } /\* End only for dummies time varying (single?) *\/ */
                   6479: /*     }else{ /\* Useless product *\/ */
                   6480: /*       /\* printf("*"); *\/ */
                   6481: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   6482: /*     } */
                   6483: /*     iposold=ipos; */
                   6484: /*       } /\* For each time varying covariate *\/ */
                   6485: /*     }/\* End debugILK *\/ */
1.207     brouard  6486:     fflush(fichtm);
1.343     brouard  6487:   }/* End globpri */
1.126     brouard  6488:   return;
                   6489: }
                   6490: 
                   6491: 
                   6492: /*********** Maximum Likelihood Estimation ***************/
                   6493: 
                   6494: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   6495: {
1.359     brouard  6496:   int i,j,  jkk=0, iter=0;
1.126     brouard  6497:   double **xi;
1.359     brouard  6498:   /*double fret;*/
                   6499:   /*double fretone;*/ /* Only one call to likelihood */
1.126     brouard  6500:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  6501:   
1.359     brouard  6502:   /*double * p1;*/ /* Shifted parameters from 0 instead of 1 */
1.162     brouard  6503: #ifdef NLOPT
                   6504:   int creturn;
                   6505:   nlopt_opt opt;
                   6506:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   6507:   double *lb;
                   6508:   double minf; /* the minimum objective value, upon return */
1.354     brouard  6509: 
1.162     brouard  6510:   myfunc_data dinst, *d = &dinst;
                   6511: #endif
                   6512: 
                   6513: 
1.126     brouard  6514:   xi=matrix(1,npar,1,npar);
1.357     brouard  6515:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  6516:     for (j=1;j<=npar;j++)
                   6517:       xi[i][j]=(i==j ? 1.0 : 0.0);
1.359     brouard  6518:   printf("Powell-prax\n");  fprintf(ficlog,"Powell-prax\n");
1.201     brouard  6519:   strcpy(filerespow,"POW_"); 
1.126     brouard  6520:   strcat(filerespow,fileres);
                   6521:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6522:     printf("Problem with resultfile: %s\n", filerespow);
                   6523:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6524:   }
                   6525:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   6526:   for (i=1;i<=nlstate;i++)
                   6527:     for(j=1;j<=nlstate+ndeath;j++)
                   6528:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6529:   fprintf(ficrespow,"\n");
1.162     brouard  6530: #ifdef POWELL
1.319     brouard  6531: #ifdef LINMINORIGINAL
                   6532: #else /* LINMINORIGINAL */
                   6533:   
                   6534:   flatdir=ivector(1,npar); 
                   6535:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   6536: #endif /*LINMINORIGINAL */
                   6537: 
                   6538: #ifdef FLATSUP
                   6539:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6540:   /* reorganizing p by suppressing flat directions */
                   6541:   for(i=1, jk=1; i <=nlstate; i++){
                   6542:     for(k=1; k <=(nlstate+ndeath); k++){
                   6543:       if (k != i) {
                   6544:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6545:         if(flatdir[jk]==1){
                   6546:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   6547:         }
                   6548:         for(j=1; j <=ncovmodel; j++){
                   6549:           printf("%12.7f ",p[jk]);
                   6550:           jk++; 
                   6551:         }
                   6552:         printf("\n");
                   6553:       }
                   6554:     }
                   6555:   }
                   6556: /* skipping */
                   6557:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   6558:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   6559:     for(k=1; k <=(nlstate+ndeath); k++){
                   6560:       if (k != i) {
                   6561:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6562:         if(flatdir[jk]==1){
                   6563:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   6564:           for(j=1; j <=ncovmodel;  jk++,j++){
                   6565:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   6566:             /*q[jjk]=p[jk];*/
                   6567:           }
                   6568:         }else{
                   6569:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   6570:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   6571:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   6572:             /*q[jjk]=p[jk];*/
                   6573:           }
                   6574:         }
                   6575:         printf("\n");
                   6576:       }
                   6577:       fflush(stdout);
                   6578:     }
                   6579:   }
                   6580:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6581: #else  /* FLATSUP */
1.359     brouard  6582: /*  powell(p,xi,npar,ftol,&iter,&fret,func);*/
                   6583: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
                   6584:   int prin=1;
                   6585:   double h0=0.25;
                   6586:   double macheps;
                   6587:   double fmin;
                   6588:   macheps=pow(16.0,-13.0);
                   6589: /* #include "praxis.h" */
                   6590:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   6591:    /* praxis ( ftol, h0, npar, prin, p, func ); */
                   6592: /* p1= (p+1); */ /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6593: printf("Praxis Gegenfurtner \n");
                   6594: fprintf(ficlog, "Praxis  Gegenfurtner\n");fflush(ficlog);
                   6595: /* praxis ( ftol, h0, npar, prin, p1, func ); */
                   6596:   /* fmin = praxis(1.e-5,macheps, h, n, prin, x, func); */
                   6597:   fmin = praxis(ftol,macheps, h0, npar, prin, p, func);
                   6598: printf("End Praxis\n");
1.319     brouard  6599: #endif  /* FLATSUP */
                   6600: 
                   6601: #ifdef LINMINORIGINAL
                   6602: #else
                   6603:       free_ivector(flatdir,1,npar); 
                   6604: #endif  /* LINMINORIGINAL*/
                   6605: #endif /* POWELL */
1.126     brouard  6606: 
1.162     brouard  6607: #ifdef NLOPT
                   6608: #ifdef NEWUOA
                   6609:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   6610: #else
                   6611:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   6612: #endif
                   6613:   lb=vector(0,npar-1);
                   6614:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   6615:   nlopt_set_lower_bounds(opt, lb);
                   6616:   nlopt_set_initial_step1(opt, 0.1);
                   6617:   
                   6618:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6619:   d->function = func;
                   6620:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   6621:   nlopt_set_min_objective(opt, myfunc, d);
                   6622:   nlopt_set_xtol_rel(opt, ftol);
                   6623:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   6624:     printf("nlopt failed! %d\n",creturn); 
                   6625:   }
                   6626:   else {
                   6627:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   6628:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   6629:     iter=1; /* not equal */
                   6630:   }
                   6631:   nlopt_destroy(opt);
                   6632: #endif
1.319     brouard  6633: #ifdef FLATSUP
                   6634:   /* npared = npar -flatd/ncovmodel; */
                   6635:   /* xired= matrix(1,npared,1,npared); */
                   6636:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   6637:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   6638:   /* free_matrix(xire,1,npared,1,npared); */
                   6639: #else  /* FLATSUP */
                   6640: #endif /* FLATSUP */
1.126     brouard  6641:   free_matrix(xi,1,npar,1,npar);
                   6642:   fclose(ficrespow);
1.203     brouard  6643:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   6644:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  6645:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  6646: 
                   6647: }
                   6648: 
                   6649: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  6650: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  6651: {
                   6652:   double  **a,**y,*x,pd;
1.203     brouard  6653:   /* double **hess; */
1.164     brouard  6654:   int i, j;
1.126     brouard  6655:   int *indx;
                   6656: 
                   6657:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  6658:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  6659:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   6660:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   6661:   double gompertz(double p[]);
1.203     brouard  6662:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  6663: 
                   6664:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   6665:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   6666:   for (i=1;i<=npar;i++){
1.203     brouard  6667:     printf("%d-",i);fflush(stdout);
                   6668:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  6669:    
                   6670:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   6671:     
                   6672:     /*  printf(" %f ",p[i]);
                   6673:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   6674:   }
                   6675:   
                   6676:   for (i=1;i<=npar;i++) {
                   6677:     for (j=1;j<=npar;j++)  {
                   6678:       if (j>i) { 
1.203     brouard  6679:        printf(".%d-%d",i,j);fflush(stdout);
                   6680:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   6681:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  6682:        
                   6683:        hess[j][i]=hess[i][j];    
                   6684:        /*printf(" %lf ",hess[i][j]);*/
                   6685:       }
                   6686:     }
                   6687:   }
                   6688:   printf("\n");
                   6689:   fprintf(ficlog,"\n");
                   6690: 
                   6691:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6692:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6693:   
                   6694:   a=matrix(1,npar,1,npar);
                   6695:   y=matrix(1,npar,1,npar);
                   6696:   x=vector(1,npar);
                   6697:   indx=ivector(1,npar);
                   6698:   for (i=1;i<=npar;i++)
                   6699:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   6700:   ludcmp(a,npar,indx,&pd);
                   6701: 
                   6702:   for (j=1;j<=npar;j++) {
                   6703:     for (i=1;i<=npar;i++) x[i]=0;
                   6704:     x[j]=1;
                   6705:     lubksb(a,npar,indx,x);
                   6706:     for (i=1;i<=npar;i++){ 
                   6707:       matcov[i][j]=x[i];
                   6708:     }
                   6709:   }
                   6710: 
                   6711:   printf("\n#Hessian matrix#\n");
                   6712:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   6713:   for (i=1;i<=npar;i++) { 
                   6714:     for (j=1;j<=npar;j++) { 
1.203     brouard  6715:       printf("%.6e ",hess[i][j]);
                   6716:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  6717:     }
                   6718:     printf("\n");
                   6719:     fprintf(ficlog,"\n");
                   6720:   }
                   6721: 
1.203     brouard  6722:   /* printf("\n#Covariance matrix#\n"); */
                   6723:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   6724:   /* for (i=1;i<=npar;i++) {  */
                   6725:   /*   for (j=1;j<=npar;j++) {  */
                   6726:   /*     printf("%.6e ",matcov[i][j]); */
                   6727:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   6728:   /*   } */
                   6729:   /*   printf("\n"); */
                   6730:   /*   fprintf(ficlog,"\n"); */
                   6731:   /* } */
                   6732: 
1.126     brouard  6733:   /* Recompute Inverse */
1.203     brouard  6734:   /* for (i=1;i<=npar;i++) */
                   6735:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   6736:   /* ludcmp(a,npar,indx,&pd); */
                   6737: 
                   6738:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   6739: 
                   6740:   /* for (j=1;j<=npar;j++) { */
                   6741:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   6742:   /*   x[j]=1; */
                   6743:   /*   lubksb(a,npar,indx,x); */
                   6744:   /*   for (i=1;i<=npar;i++){  */
                   6745:   /*     y[i][j]=x[i]; */
                   6746:   /*     printf("%.3e ",y[i][j]); */
                   6747:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   6748:   /*   } */
                   6749:   /*   printf("\n"); */
                   6750:   /*   fprintf(ficlog,"\n"); */
                   6751:   /* } */
                   6752: 
                   6753:   /* Verifying the inverse matrix */
                   6754: #ifdef DEBUGHESS
                   6755:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  6756: 
1.203     brouard  6757:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   6758:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  6759: 
                   6760:   for (j=1;j<=npar;j++) {
                   6761:     for (i=1;i<=npar;i++){ 
1.203     brouard  6762:       printf("%.2f ",y[i][j]);
                   6763:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  6764:     }
                   6765:     printf("\n");
                   6766:     fprintf(ficlog,"\n");
                   6767:   }
1.203     brouard  6768: #endif
1.126     brouard  6769: 
                   6770:   free_matrix(a,1,npar,1,npar);
                   6771:   free_matrix(y,1,npar,1,npar);
                   6772:   free_vector(x,1,npar);
                   6773:   free_ivector(indx,1,npar);
1.203     brouard  6774:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  6775: 
                   6776: 
                   6777: }
                   6778: 
                   6779: /*************** hessian matrix ****************/
                   6780: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  6781: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  6782:   int i;
                   6783:   int l=1, lmax=20;
1.203     brouard  6784:   double k1,k2, res, fx;
1.132     brouard  6785:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  6786:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   6787:   int k=0,kmax=10;
                   6788:   double l1;
                   6789: 
                   6790:   fx=func(x);
                   6791:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  6792:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  6793:     l1=pow(10,l);
                   6794:     delts=delt;
                   6795:     for(k=1 ; k <kmax; k=k+1){
                   6796:       delt = delta*(l1*k);
                   6797:       p2[theta]=x[theta] +delt;
1.145     brouard  6798:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  6799:       p2[theta]=x[theta]-delt;
                   6800:       k2=func(p2)-fx;
                   6801:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  6802:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  6803:       
1.203     brouard  6804: #ifdef DEBUGHESSII
1.126     brouard  6805:       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);
                   6806:       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);
                   6807: #endif
                   6808:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   6809:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   6810:        k=kmax;
                   6811:       }
                   6812:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  6813:        k=kmax; l=lmax*10;
1.126     brouard  6814:       }
                   6815:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   6816:        delts=delt;
                   6817:       }
1.203     brouard  6818:     } /* End loop k */
1.126     brouard  6819:   }
                   6820:   delti[theta]=delts;
                   6821:   return res; 
                   6822:   
                   6823: }
                   6824: 
1.203     brouard  6825: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  6826: {
                   6827:   int i;
1.164     brouard  6828:   int l=1, lmax=20;
1.126     brouard  6829:   double k1,k2,k3,k4,res,fx;
1.132     brouard  6830:   double p2[MAXPARM+1];
1.203     brouard  6831:   int k, kmax=1;
                   6832:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  6833: 
                   6834:   int firstime=0;
1.203     brouard  6835:   
1.126     brouard  6836:   fx=func(x);
1.203     brouard  6837:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  6838:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  6839:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6840:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6841:     k1=func(p2)-fx;
                   6842:   
1.203     brouard  6843:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6844:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6845:     k2=func(p2)-fx;
                   6846:   
1.203     brouard  6847:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6848:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6849:     k3=func(p2)-fx;
                   6850:   
1.203     brouard  6851:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6852:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6853:     k4=func(p2)-fx;
1.203     brouard  6854:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   6855:     if(k1*k2*k3*k4 <0.){
1.208     brouard  6856:       firstime=1;
1.203     brouard  6857:       kmax=kmax+10;
1.208     brouard  6858:     }
                   6859:     if(kmax >=10 || firstime ==1){
1.354     brouard  6860:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  6861:       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);
                   6862:       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  6863:       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);
                   6864:       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);
                   6865:     }
                   6866: #ifdef DEBUGHESSIJ
                   6867:     v1=hess[thetai][thetai];
                   6868:     v2=hess[thetaj][thetaj];
                   6869:     cv12=res;
                   6870:     /* Computing eigen value of Hessian matrix */
                   6871:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6872:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6873:     if ((lc2 <0) || (lc1 <0) ){
                   6874:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6875:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6876:       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);
                   6877:       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);
                   6878:     }
1.126     brouard  6879: #endif
                   6880:   }
                   6881:   return res;
                   6882: }
                   6883: 
1.203     brouard  6884:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   6885: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   6886: /* { */
                   6887: /*   int i; */
                   6888: /*   int l=1, lmax=20; */
                   6889: /*   double k1,k2,k3,k4,res,fx; */
                   6890: /*   double p2[MAXPARM+1]; */
                   6891: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   6892: /*   int k=0,kmax=10; */
                   6893: /*   double l1; */
                   6894:   
                   6895: /*   fx=func(x); */
                   6896: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   6897: /*     l1=pow(10,l); */
                   6898: /*     delts=delt; */
                   6899: /*     for(k=1 ; k <kmax; k=k+1){ */
                   6900: /*       delt = delti*(l1*k); */
                   6901: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   6902: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6903: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6904: /*       k1=func(p2)-fx; */
                   6905:       
                   6906: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6907: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6908: /*       k2=func(p2)-fx; */
                   6909:       
                   6910: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6911: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6912: /*       k3=func(p2)-fx; */
                   6913:       
                   6914: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6915: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6916: /*       k4=func(p2)-fx; */
                   6917: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   6918: /* #ifdef DEBUGHESSIJ */
                   6919: /*       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); */
                   6920: /*       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); */
                   6921: /* #endif */
                   6922: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   6923: /*     k=kmax; */
                   6924: /*       } */
                   6925: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   6926: /*     k=kmax; l=lmax*10; */
                   6927: /*       } */
                   6928: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   6929: /*     delts=delt; */
                   6930: /*       } */
                   6931: /*     } /\* End loop k *\/ */
                   6932: /*   } */
                   6933: /*   delti[theta]=delts; */
                   6934: /*   return res;  */
                   6935: /* } */
                   6936: 
                   6937: 
1.126     brouard  6938: /************** Inverse of matrix **************/
                   6939: void ludcmp(double **a, int n, int *indx, double *d) 
                   6940: { 
                   6941:   int i,imax,j,k; 
                   6942:   double big,dum,sum,temp; 
                   6943:   double *vv; 
                   6944:  
                   6945:   vv=vector(1,n); 
                   6946:   *d=1.0; 
                   6947:   for (i=1;i<=n;i++) { 
                   6948:     big=0.0; 
                   6949:     for (j=1;j<=n;j++) 
                   6950:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  6951:     if (big == 0.0){
                   6952:       printf(" Singular Hessian matrix at row %d:\n",i);
                   6953:       for (j=1;j<=n;j++) {
                   6954:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   6955:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   6956:       }
                   6957:       fflush(ficlog);
                   6958:       fclose(ficlog);
                   6959:       nrerror("Singular matrix in routine ludcmp"); 
                   6960:     }
1.126     brouard  6961:     vv[i]=1.0/big; 
                   6962:   } 
                   6963:   for (j=1;j<=n;j++) { 
                   6964:     for (i=1;i<j;i++) { 
                   6965:       sum=a[i][j]; 
                   6966:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   6967:       a[i][j]=sum; 
                   6968:     } 
                   6969:     big=0.0; 
                   6970:     for (i=j;i<=n;i++) { 
                   6971:       sum=a[i][j]; 
                   6972:       for (k=1;k<j;k++) 
                   6973:        sum -= a[i][k]*a[k][j]; 
                   6974:       a[i][j]=sum; 
                   6975:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   6976:        big=dum; 
                   6977:        imax=i; 
                   6978:       } 
                   6979:     } 
                   6980:     if (j != imax) { 
                   6981:       for (k=1;k<=n;k++) { 
                   6982:        dum=a[imax][k]; 
                   6983:        a[imax][k]=a[j][k]; 
                   6984:        a[j][k]=dum; 
                   6985:       } 
                   6986:       *d = -(*d); 
                   6987:       vv[imax]=vv[j]; 
                   6988:     } 
                   6989:     indx[j]=imax; 
                   6990:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   6991:     if (j != n) { 
                   6992:       dum=1.0/(a[j][j]); 
                   6993:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   6994:     } 
                   6995:   } 
                   6996:   free_vector(vv,1,n);  /* Doesn't work */
                   6997: ;
                   6998: } 
                   6999: 
                   7000: void lubksb(double **a, int n, int *indx, double b[]) 
                   7001: { 
                   7002:   int i,ii=0,ip,j; 
                   7003:   double sum; 
                   7004:  
                   7005:   for (i=1;i<=n;i++) { 
                   7006:     ip=indx[i]; 
                   7007:     sum=b[ip]; 
                   7008:     b[ip]=b[i]; 
                   7009:     if (ii) 
                   7010:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   7011:     else if (sum) ii=i; 
                   7012:     b[i]=sum; 
                   7013:   } 
                   7014:   for (i=n;i>=1;i--) { 
                   7015:     sum=b[i]; 
                   7016:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   7017:     b[i]=sum/a[i][i]; 
                   7018:   } 
                   7019: } 
                   7020: 
                   7021: void pstamp(FILE *fichier)
                   7022: {
1.196     brouard  7023:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  7024: }
                   7025: 
1.297     brouard  7026: void date2dmy(double date,double *day, double *month, double *year){
                   7027:   double yp=0., yp1=0., yp2=0.;
                   7028:   
                   7029:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   7030:                        fractional in yp1 */
                   7031:   *year=yp;
                   7032:   yp2=modf((yp1*12),&yp);
                   7033:   *month=yp;
                   7034:   yp1=modf((yp2*30.5),&yp);
                   7035:   *day=yp;
                   7036:   if(*day==0) *day=1;
                   7037:   if(*month==0) *month=1;
                   7038: }
                   7039: 
1.253     brouard  7040: 
                   7041: 
1.126     brouard  7042: /************ Frequencies ********************/
1.251     brouard  7043: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  7044:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   7045:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  7046: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  7047:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  7048:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  7049:   int iind=0, iage=0;
                   7050:   int mi; /* Effective wave */
                   7051:   int first;
                   7052:   double ***freq; /* Frequencies */
1.268     brouard  7053:   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 */
                   7054:   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  7055:   double *meanq, *stdq, *idq;
1.226     brouard  7056:   double **meanqt;
                   7057:   double *pp, **prop, *posprop, *pospropt;
                   7058:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   7059:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   7060:   double agebegin, ageend;
                   7061:     
                   7062:   pp=vector(1,nlstate);
1.251     brouard  7063:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  7064:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   7065:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   7066:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   7067:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  7068:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  7069:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  7070:   meanqt=matrix(1,lastpass,1,nqtveff);
                   7071:   strcpy(fileresp,"P_");
                   7072:   strcat(fileresp,fileresu);
                   7073:   /*strcat(fileresphtm,fileresu);*/
                   7074:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   7075:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   7076:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   7077:     exit(0);
                   7078:   }
1.240     brouard  7079:   
1.226     brouard  7080:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   7081:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   7082:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7083:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7084:     fflush(ficlog);
                   7085:     exit(70); 
                   7086:   }
                   7087:   else{
                   7088:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  7089: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  7090: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7091:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7092:   }
1.319     brouard  7093:   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  7094:   
1.226     brouard  7095:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   7096:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   7097:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7098:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7099:     fflush(ficlog);
                   7100:     exit(70); 
1.240     brouard  7101:   } else{
1.226     brouard  7102:     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  7103: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  7104: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7105:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7106:   }
1.319     brouard  7107:   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  7108:   
1.253     brouard  7109:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   7110:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  7111:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  7112:   j1=0;
1.126     brouard  7113:   
1.227     brouard  7114:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  7115:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  7116:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  7117:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  7118:   
                   7119:   
1.226     brouard  7120:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   7121:      reference=low_education V1=0,V2=0
                   7122:      med_educ                V1=1 V2=0, 
                   7123:      high_educ               V1=0 V2=1
1.330     brouard  7124:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  7125:   */
1.249     brouard  7126:   dateintsum=0;
                   7127:   k2cpt=0;
                   7128: 
1.253     brouard  7129:   if(cptcoveff == 0 )
1.265     brouard  7130:     nl=1;  /* Constant and age model only */
1.253     brouard  7131:   else
                   7132:     nl=2;
1.265     brouard  7133: 
                   7134:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   7135:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  7136:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  7137:    *     freq[s1][s2][iage] =0.
                   7138:    *     Loop on iind
                   7139:    *       ++freq[s1][s2][iage] weighted
                   7140:    *     end iind
                   7141:    *     if covariate and j!0
                   7142:    *       headers Variable on one line
                   7143:    *     endif cov j!=0
                   7144:    *     header of frequency table by age
                   7145:    *     Loop on age
                   7146:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   7147:    *       pos+=freq[s1][s2][iage] weighted
                   7148:    *       Loop on s1 initial state
                   7149:    *         fprintf(ficresp
                   7150:    *       end s1
                   7151:    *     end age
                   7152:    *     if j!=0 computes starting values
                   7153:    *     end compute starting values
                   7154:    *   end j1
                   7155:    * end nl 
                   7156:    */
1.253     brouard  7157:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   7158:     if(nj==1)
                   7159:       j=0;  /* First pass for the constant */
1.265     brouard  7160:     else{
1.335     brouard  7161:       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  7162:     }
1.251     brouard  7163:     first=1;
1.332     brouard  7164:     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  7165:       posproptt=0.;
1.330     brouard  7166:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  7167:        scanf("%d", i);*/
                   7168:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  7169:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  7170:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  7171:            freq[i][s2][m]=0;
1.251     brouard  7172:       
                   7173:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  7174:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  7175:          prop[i][m]=0;
                   7176:        posprop[i]=0;
                   7177:        pospropt[i]=0;
                   7178:       }
1.283     brouard  7179:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  7180:         idq[z1]=0.;
                   7181:         meanq[z1]=0.;
                   7182:         stdq[z1]=0.;
1.283     brouard  7183:       }
                   7184:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  7185:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  7186:       /*         meanqt[m][z1]=0.; */
                   7187:       /*       } */
                   7188:       /* }       */
1.251     brouard  7189:       /* dateintsum=0; */
                   7190:       /* k2cpt=0; */
                   7191:       
1.265     brouard  7192:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  7193:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   7194:        bool=1;
                   7195:        if(j !=0){
                   7196:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  7197:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   7198:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  7199:                /* if(Tvaraff[z1] ==-20){ */
                   7200:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   7201:                /* }else  if(Tvaraff[z1] ==-10){ */
                   7202:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  7203:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  7204:                /* 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); */
                   7205:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  7206:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  7207:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  7208:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  7209:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  7210:                  /* 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", */
                   7211:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   7212:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  7213:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   7214:                } /* Onlyf fixed */
                   7215:              } /* end z1 */
1.335     brouard  7216:            } /* cptcoveff > 0 */
1.251     brouard  7217:          } /* end any */
                   7218:        }/* end j==0 */
1.265     brouard  7219:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  7220:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  7221:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  7222:            m=mw[mi][iind];
                   7223:            if(j!=0){
                   7224:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  7225:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  7226:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7227:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   7228:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  7229:                    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  7230:                                                                                      value is -1, we don't select. It differs from the 
                   7231:                                                                                      constant and age model which counts them. */
                   7232:                      bool=0; /* not selected */
                   7233:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  7234:                    /* i1=Tvaraff[z1]; */
                   7235:                    /* i2=TnsdVar[i1]; */
                   7236:                    /* i3=nbcode[i1][i2]; */
                   7237:                    /* i4=covar[i1][iind]; */
                   7238:                    /* if(i4 != i3){ */
                   7239:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  7240:                      bool=0;
                   7241:                    }
                   7242:                  }
                   7243:                }
                   7244:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   7245:            } /* end j==0 */
                   7246:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  7247:            if(bool==1){ /*Selected */
1.251     brouard  7248:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   7249:                 and mw[mi+1][iind]. dh depends on stepm. */
                   7250:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   7251:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   7252:              if(m >=firstpass && m <=lastpass){
                   7253:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   7254:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   7255:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   7256:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   7257:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   7258:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   7259:                if (m<lastpass) {
                   7260:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   7261:                  /*   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]); */
                   7262:                  if(s[m][iind]==-1)
                   7263:                    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.));
                   7264:                  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  7265:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   7266:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  7267:                      idq[z1]=idq[z1]+weight[iind];
                   7268:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   7269:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   7270:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  7271:                    }
1.284     brouard  7272:                  }
1.251     brouard  7273:                  /* if((int)agev[m][iind] == 55) */
                   7274:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   7275:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   7276:                  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  7277:                }
1.251     brouard  7278:              } /* end if between passes */  
                   7279:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   7280:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   7281:                k2cpt++;
                   7282:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  7283:              }
1.251     brouard  7284:            }else{
                   7285:              bool=1;
                   7286:            }/* end bool 2 */
                   7287:          } /* end m */
1.284     brouard  7288:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   7289:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   7290:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   7291:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   7292:          /* } */
1.251     brouard  7293:        } /* end bool */
                   7294:       } /* end iind = 1 to imx */
1.319     brouard  7295:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  7296:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   7297:       
                   7298:       
                   7299:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  7300:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  7301:         pstamp(ficresp);
1.335     brouard  7302:       if  (cptcoveff>0 && j!=0){
1.265     brouard  7303:         pstamp(ficresp);
1.251     brouard  7304:        printf( "\n#********** Variable "); 
                   7305:        fprintf(ficresp, "\n#********** Variable "); 
                   7306:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   7307:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   7308:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  7309:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  7310:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  7311:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7312:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7313:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7314:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7315:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  7316:          }else{
1.330     brouard  7317:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7318:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7319:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7320:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7321:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  7322:          }
                   7323:        }
                   7324:        printf( "**********\n#");
                   7325:        fprintf(ficresp, "**********\n#");
                   7326:        fprintf(ficresphtm, "**********</h3>\n");
                   7327:        fprintf(ficresphtmfr, "**********</h3>\n");
                   7328:        fprintf(ficlog, "**********\n");
                   7329:       }
1.284     brouard  7330:       /*
                   7331:        Printing means of quantitative variables if any
                   7332:       */
                   7333:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  7334:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  7335:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  7336:        if(weightopt==1){
                   7337:          printf(" Weighted mean and standard deviation of");
                   7338:          fprintf(ficlog," Weighted mean and standard deviation of");
                   7339:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   7340:        }
1.311     brouard  7341:        /* mu = \frac{w x}{\sum w}
                   7342:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   7343:        */
                   7344:        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]));
                   7345:        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]));
                   7346:        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  7347:       }
                   7348:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   7349:       /*       for(m=1;m<=lastpass;m++){ */
                   7350:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   7351:       /*   } */
                   7352:       /* } */
1.283     brouard  7353: 
1.251     brouard  7354:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  7355:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  7356:         fprintf(ficresp, " Age");
1.335     brouard  7357:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   7358:          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]]);
                   7359:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7360:        }
1.251     brouard  7361:       for(i=1; i<=nlstate;i++) {
1.335     brouard  7362:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  7363:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   7364:       }
1.335     brouard  7365:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  7366:       fprintf(ficresphtm, "\n");
                   7367:       
                   7368:       /* Header of frequency table by age */
                   7369:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   7370:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  7371:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  7372:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7373:          if(s2!=0 && m!=0)
                   7374:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  7375:        }
1.226     brouard  7376:       }
1.251     brouard  7377:       fprintf(ficresphtmfr, "\n");
                   7378:     
                   7379:       /* For each age */
                   7380:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   7381:        fprintf(ficresphtm,"<tr>");
                   7382:        if(iage==iagemax+1){
                   7383:          fprintf(ficlog,"1");
                   7384:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   7385:        }else if(iage==iagemax+2){
                   7386:          fprintf(ficlog,"0");
                   7387:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   7388:        }else if(iage==iagemax+3){
                   7389:          fprintf(ficlog,"Total");
                   7390:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   7391:        }else{
1.240     brouard  7392:          if(first==1){
1.251     brouard  7393:            first=0;
                   7394:            printf("See log file for details...\n");
                   7395:          }
                   7396:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   7397:          fprintf(ficlog,"Age %d", iage);
                   7398:        }
1.265     brouard  7399:        for(s1=1; s1 <=nlstate ; s1++){
                   7400:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   7401:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  7402:        }
1.265     brouard  7403:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7404:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  7405:            pos += freq[s1][m][iage];
                   7406:          if(pp[s1]>=1.e-10){
1.251     brouard  7407:            if(first==1){
1.265     brouard  7408:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7409:            }
1.265     brouard  7410:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7411:          }else{
                   7412:            if(first==1)
1.265     brouard  7413:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   7414:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  7415:          }
                   7416:        }
                   7417:       
1.265     brouard  7418:        for(s1=1; s1 <=nlstate ; s1++){ 
                   7419:          /* posprop[s1]=0; */
                   7420:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   7421:            pp[s1] += freq[s1][m][iage];
                   7422:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   7423:       
                   7424:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   7425:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   7426:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7427:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7428:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7429:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7430:        }
                   7431:        
                   7432:        /* Writing ficresp */
1.335     brouard  7433:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7434:           if( iage <= iagemax){
                   7435:            fprintf(ficresp," %d",iage);
                   7436:           }
                   7437:         }else if( nj==2){
                   7438:           if( iage <= iagemax){
                   7439:            fprintf(ficresp," %d",iage);
1.335     brouard  7440:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  7441:           }
1.240     brouard  7442:        }
1.265     brouard  7443:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  7444:          if(pos>=1.e-5){
1.251     brouard  7445:            if(first==1)
1.265     brouard  7446:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   7447:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  7448:          }else{
                   7449:            if(first==1)
1.265     brouard  7450:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   7451:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  7452:          }
                   7453:          if( iage <= iagemax){
                   7454:            if(pos>=1.e-5){
1.335     brouard  7455:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7456:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7457:               }else if( nj==2){
                   7458:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7459:               }
                   7460:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7461:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   7462:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   7463:            } else{
1.335     brouard  7464:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  7465:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  7466:            }
1.240     brouard  7467:          }
1.265     brouard  7468:          pospropt[s1] +=posprop[s1];
                   7469:        } /* end loop s1 */
1.251     brouard  7470:        /* pospropt=0.; */
1.265     brouard  7471:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  7472:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7473:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  7474:              if(first==1){
1.265     brouard  7475:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7476:              }
1.265     brouard  7477:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   7478:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7479:            }
1.265     brouard  7480:            if(s1!=0 && m!=0)
                   7481:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  7482:          }
1.265     brouard  7483:        } /* end loop s1 */
1.251     brouard  7484:        posproptt=0.; 
1.265     brouard  7485:        for(s1=1; s1 <=nlstate; s1++){
                   7486:          posproptt += pospropt[s1];
1.251     brouard  7487:        }
                   7488:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  7489:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  7490:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  7491:          if(iage <= iagemax)
                   7492:            fprintf(ficresp,"\n");
1.240     brouard  7493:        }
1.251     brouard  7494:        if(first==1)
                   7495:          printf("Others in log...\n");
                   7496:        fprintf(ficlog,"\n");
                   7497:       } /* end loop age iage */
1.265     brouard  7498:       
1.251     brouard  7499:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  7500:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7501:        if(posproptt < 1.e-5){
1.265     brouard  7502:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  7503:        }else{
1.265     brouard  7504:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  7505:        }
1.226     brouard  7506:       }
1.251     brouard  7507:       fprintf(ficresphtm,"</tr>\n");
                   7508:       fprintf(ficresphtm,"</table>\n");
                   7509:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  7510:       if(posproptt < 1.e-5){
1.251     brouard  7511:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   7512:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  7513:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   7514:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  7515:        invalidvarcomb[j1]=1;
1.226     brouard  7516:       }else{
1.338     brouard  7517:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  7518:        invalidvarcomb[j1]=0;
1.226     brouard  7519:       }
1.251     brouard  7520:       fprintf(ficresphtmfr,"</table>\n");
                   7521:       fprintf(ficlog,"\n");
                   7522:       if(j!=0){
                   7523:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  7524:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7525:          for(k=1; k <=(nlstate+ndeath); k++){
                   7526:            if (k != i) {
1.265     brouard  7527:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  7528:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  7529:                  if(j1==1){ /* All dummy covariates to zero */
                   7530:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   7531:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  7532:                    printf("%d%d ",i,k);
                   7533:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7534:                    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]));
                   7535:                    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]));
                   7536:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  7537:                  }
1.253     brouard  7538:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   7539:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   7540:                    x[iage]= (double)iage;
                   7541:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  7542:                    /* 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  7543:                  }
1.268     brouard  7544:                  /* Some are not finite, but linreg will ignore these ages */
                   7545:                  no=0;
1.253     brouard  7546:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  7547:                  pstart[s1]=b;
                   7548:                  pstart[s1-1]=a;
1.252     brouard  7549:                }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 */ 
                   7550:                  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]);
                   7551:                  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  7552:                  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  7553:                  printf("%d%d ",i,k);
                   7554:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7555:                  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  7556:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   7557:                  ;
                   7558:                }
                   7559:                /* printf("%12.7f )", param[i][jj][k]); */
                   7560:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7561:                s1++; 
1.251     brouard  7562:              } /* end jj */
                   7563:            } /* end k!= i */
                   7564:          } /* end k */
1.265     brouard  7565:        } /* end i, s1 */
1.251     brouard  7566:       } /* end j !=0 */
                   7567:     } /* end selected combination of covariate j1 */
                   7568:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   7569:       printf("#Freqsummary: Starting values for the constants:\n");
                   7570:       fprintf(ficlog,"\n");
1.265     brouard  7571:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7572:        for(k=1; k <=(nlstate+ndeath); k++){
                   7573:          if (k != i) {
                   7574:            printf("%d%d ",i,k);
                   7575:            fprintf(ficlog,"%d%d ",i,k);
                   7576:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  7577:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  7578:              if(jj==1){ /* Age has to be done */
1.265     brouard  7579:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   7580:                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]));
                   7581:                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  7582:              }
                   7583:              /* printf("%12.7f )", param[i][jj][k]); */
                   7584:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7585:              s1++; 
1.250     brouard  7586:            }
1.251     brouard  7587:            printf("\n");
                   7588:            fprintf(ficlog,"\n");
1.250     brouard  7589:          }
                   7590:        }
1.284     brouard  7591:       } /* end of state i */
1.251     brouard  7592:       printf("#Freqsummary\n");
                   7593:       fprintf(ficlog,"\n");
1.265     brouard  7594:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   7595:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   7596:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   7597:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7598:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7599:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   7600:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   7601:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  7602:          /* } */
                   7603:        }
1.265     brouard  7604:       } /* end loop s1 */
1.251     brouard  7605:       
                   7606:       printf("\n");
                   7607:       fprintf(ficlog,"\n");
                   7608:     } /* end j=0 */
1.249     brouard  7609:   } /* end j */
1.252     brouard  7610: 
1.253     brouard  7611:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  7612:     for(i=1, jk=1; i <=nlstate; i++){
                   7613:       for(j=1; j <=nlstate+ndeath; j++){
                   7614:        if(j!=i){
                   7615:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7616:          printf("%1d%1d",i,j);
                   7617:          fprintf(ficparo,"%1d%1d",i,j);
                   7618:          for(k=1; k<=ncovmodel;k++){
                   7619:            /*    printf(" %lf",param[i][j][k]); */
                   7620:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   7621:            p[jk]=pstart[jk];
                   7622:            printf(" %f ",pstart[jk]);
                   7623:            fprintf(ficparo," %f ",pstart[jk]);
                   7624:            jk++;
                   7625:          }
                   7626:          printf("\n");
                   7627:          fprintf(ficparo,"\n");
                   7628:        }
                   7629:       }
                   7630:     }
                   7631:   } /* end mle=-2 */
1.226     brouard  7632:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  7633:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  7634:   
1.226     brouard  7635:   fclose(ficresp);
                   7636:   fclose(ficresphtm);
                   7637:   fclose(ficresphtmfr);
1.283     brouard  7638:   free_vector(idq,1,nqfveff);
1.226     brouard  7639:   free_vector(meanq,1,nqfveff);
1.284     brouard  7640:   free_vector(stdq,1,nqfveff);
1.226     brouard  7641:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  7642:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   7643:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  7644:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7645:   free_vector(pospropt,1,nlstate);
                   7646:   free_vector(posprop,1,nlstate);
1.251     brouard  7647:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7648:   free_vector(pp,1,nlstate);
                   7649:   /* End of freqsummary */
                   7650: }
1.126     brouard  7651: 
1.268     brouard  7652: /* Simple linear regression */
                   7653: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   7654: 
                   7655:   /* y=a+bx regression */
                   7656:   double   sumx = 0.0;                        /* sum of x                      */
                   7657:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   7658:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   7659:   double   sumy = 0.0;                        /* sum of y                      */
                   7660:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   7661:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   7662:   double yhat;
                   7663:   
                   7664:   double denom=0;
                   7665:   int i;
                   7666:   int ne=*no;
                   7667:   
                   7668:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7669:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7670:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7671:       continue;
                   7672:     }
                   7673:     ne=ne+1;
                   7674:     sumx  += x[i];       
                   7675:     sumx2 += x[i]*x[i];  
                   7676:     sumxy += x[i] * y[i];
                   7677:     sumy  += y[i];      
                   7678:     sumy2 += y[i]*y[i]; 
                   7679:     denom = (ne * sumx2 - sumx*sumx);
                   7680:     /* 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); */
                   7681:   } 
                   7682:   
                   7683:   denom = (ne * sumx2 - sumx*sumx);
                   7684:   if (denom == 0) {
                   7685:     // vertical, slope m is infinity
                   7686:     *b = INFINITY;
                   7687:     *a = 0;
                   7688:     if (r) *r = 0;
                   7689:     return 1;
                   7690:   }
                   7691:   
                   7692:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   7693:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   7694:   if (r!=NULL) {
                   7695:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   7696:       sqrt((sumx2 - sumx*sumx/ne) *
                   7697:           (sumy2 - sumy*sumy/ne));
                   7698:   }
                   7699:   *no=ne;
                   7700:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7701:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7702:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7703:       continue;
                   7704:     }
                   7705:     ne=ne+1;
                   7706:     yhat = y[i] - *a -*b* x[i];
                   7707:     sume2  += yhat * yhat ;       
                   7708:     
                   7709:     denom = (ne * sumx2 - sumx*sumx);
                   7710:     /* 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); */
                   7711:   } 
                   7712:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   7713:   *sa= *sb * sqrt(sumx2/ne);
                   7714:   
                   7715:   return 0; 
                   7716: }
                   7717: 
1.126     brouard  7718: /************ Prevalence ********************/
1.227     brouard  7719: 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)
                   7720: {  
                   7721:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7722:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7723:      We still use firstpass and lastpass as another selection.
                   7724:   */
1.126     brouard  7725:  
1.227     brouard  7726:   int i, m, jk, j1, bool, z1,j, iv;
                   7727:   int mi; /* Effective wave */
                   7728:   int iage;
1.359     brouard  7729:   double agebegin; /*, ageend;*/
1.227     brouard  7730: 
                   7731:   double **prop;
                   7732:   double posprop; 
                   7733:   double  y2; /* in fractional years */
                   7734:   int iagemin, iagemax;
                   7735:   int first; /** to stop verbosity which is redirected to log file */
                   7736: 
                   7737:   iagemin= (int) agemin;
                   7738:   iagemax= (int) agemax;
                   7739:   /*pp=vector(1,nlstate);*/
1.251     brouard  7740:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  7741:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   7742:   j1=0;
1.222     brouard  7743:   
1.227     brouard  7744:   /*j=cptcoveff;*/
                   7745:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  7746:   
1.288     brouard  7747:   first=0;
1.335     brouard  7748:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  7749:     for (i=1; i<=nlstate; i++)  
1.251     brouard  7750:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  7751:        prop[i][iage]=0.0;
                   7752:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   7753:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   7754:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   7755:     
                   7756:     for (i=1; i<=imx; i++) { /* Each individual */
                   7757:       bool=1;
                   7758:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   7759:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   7760:        m=mw[mi][i];
                   7761:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   7762:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   7763:        for (z1=1; z1<=cptcoveff; z1++){
                   7764:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7765:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  7766:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  7767:              bool=0;
                   7768:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  7769:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  7770:              bool=0;
                   7771:            }
                   7772:        }
                   7773:        if(bool==1){ /* Otherwise we skip that wave/person */
                   7774:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   7775:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   7776:          if(m >=firstpass && m <=lastpass){
                   7777:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   7778:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   7779:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   7780:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  7781:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  7782:                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); 
                   7783:                exit(1);
                   7784:              }
                   7785:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   7786:                /*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]]);*/
                   7787:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   7788:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   7789:              } /* end valid statuses */ 
                   7790:            } /* end selection of dates */
                   7791:          } /* end selection of waves */
                   7792:        } /* end bool */
                   7793:       } /* end wave */
                   7794:     } /* end individual */
                   7795:     for(i=iagemin; i <= iagemax+3; i++){  
                   7796:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   7797:        posprop += prop[jk][i]; 
                   7798:       } 
                   7799:       
                   7800:       for(jk=1; jk <=nlstate ; jk++){      
                   7801:        if( i <=  iagemax){ 
                   7802:          if(posprop>=1.e-5){ 
                   7803:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   7804:          } else{
1.288     brouard  7805:            if(!first){
                   7806:              first=1;
1.266     brouard  7807:              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]);
                   7808:            }else{
1.288     brouard  7809:              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  7810:            }
                   7811:          }
                   7812:        } 
                   7813:       }/* end jk */ 
                   7814:     }/* end i */ 
1.222     brouard  7815:      /*} *//* end i1 */
1.227     brouard  7816:   } /* end j1 */
1.222     brouard  7817:   
1.227     brouard  7818:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   7819:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  7820:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  7821: }  /* End of prevalence */
1.126     brouard  7822: 
                   7823: /************* Waves Concatenation ***************/
                   7824: 
                   7825: 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)
                   7826: {
1.298     brouard  7827:   /* 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  7828:      Death is a valid wave (if date is known).
                   7829:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   7830:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  7831:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  7832:   */
1.126     brouard  7833: 
1.224     brouard  7834:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  7835:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   7836:      double sum=0., jmean=0.;*/
1.224     brouard  7837:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  7838:   int j, k=0,jk, ju, jl;
                   7839:   double sum=0.;
                   7840:   first=0;
1.214     brouard  7841:   firstwo=0;
1.217     brouard  7842:   firsthree=0;
1.218     brouard  7843:   firstfour=0;
1.164     brouard  7844:   jmin=100000;
1.126     brouard  7845:   jmax=-1;
                   7846:   jmean=0.;
1.224     brouard  7847: 
                   7848: /* Treating live states */
1.214     brouard  7849:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  7850:     mi=0;  /* First valid wave */
1.227     brouard  7851:     mli=0; /* Last valid wave */
1.309     brouard  7852:     m=firstpass;  /* Loop on waves */
                   7853:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  7854:       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 */
                   7855:        mli=m-1;/* mw[++mi][i]=m-1; */
                   7856:       }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  7857:        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  7858:        mli=m;
1.224     brouard  7859:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   7860:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  7861:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  7862:       }
1.309     brouard  7863:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  7864: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  7865:        break;
1.224     brouard  7866: #else
1.317     brouard  7867:        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  7868:          if(firsthree == 0){
1.302     brouard  7869:            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  7870:            firsthree=1;
1.317     brouard  7871:          }else if(firsthree >=1 && firsthree < 10){
                   7872:            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);
                   7873:            firsthree++;
                   7874:          }else if(firsthree == 10){
                   7875:            printf("Information, too many Information flags: no more reported to log either\n");
                   7876:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   7877:            firsthree++;
                   7878:          }else{
                   7879:            firsthree++;
1.227     brouard  7880:          }
1.309     brouard  7881:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  7882:          mli=m;
                   7883:        }
                   7884:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   7885:          nbwarn++;
1.309     brouard  7886:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  7887:            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);
                   7888:            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);
                   7889:          }
                   7890:          break;
                   7891:        }
                   7892:        break;
1.224     brouard  7893: #endif
1.227     brouard  7894:       }/* End m >= lastpass */
1.126     brouard  7895:     }/* end while */
1.224     brouard  7896: 
1.227     brouard  7897:     /* 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  7898:     /* After last pass */
1.224     brouard  7899: /* Treating death states */
1.214     brouard  7900:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  7901:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   7902:       /* } */
1.126     brouard  7903:       mi++;    /* Death is another wave */
                   7904:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  7905:       /* Only death is a correct wave */
1.126     brouard  7906:       mw[mi][i]=m;
1.257     brouard  7907:     } /* else not in a death state */
1.224     brouard  7908: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  7909:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  7910:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  7911:        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  7912:          nbwarn++;
                   7913:          if(firstfiv==0){
1.309     brouard  7914:            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  7915:            firstfiv=1;
                   7916:          }else{
1.309     brouard  7917:            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  7918:          }
1.309     brouard  7919:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   7920:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  7921:          nberr++;
                   7922:          if(firstwo==0){
1.309     brouard  7923:            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  7924:            firstwo=1;
                   7925:          }
1.309     brouard  7926:          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  7927:        }
1.257     brouard  7928:       }else{ /* if date of interview is unknown */
1.227     brouard  7929:        /* death is known but not confirmed by death status at any wave */
                   7930:        if(firstfour==0){
1.309     brouard  7931:          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  7932:          firstfour=1;
                   7933:        }
1.309     brouard  7934:        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  7935:       }
1.224     brouard  7936:     } /* end if date of death is known */
                   7937: #endif
1.309     brouard  7938:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   7939:     /* wav[i]=mw[mi][i];   */
1.126     brouard  7940:     if(mi==0){
                   7941:       nbwarn++;
                   7942:       if(first==0){
1.227     brouard  7943:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   7944:        first=1;
1.126     brouard  7945:       }
                   7946:       if(first==1){
1.227     brouard  7947:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  7948:       }
                   7949:     } /* end mi==0 */
                   7950:   } /* End individuals */
1.214     brouard  7951:   /* wav and mw are no more changed */
1.223     brouard  7952:        
1.317     brouard  7953:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7954:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7955: 
                   7956: 
1.126     brouard  7957:   for(i=1; i<=imx; i++){
                   7958:     for(mi=1; mi<wav[i];mi++){
                   7959:       if (stepm <=0)
1.227     brouard  7960:        dh[mi][i]=1;
1.126     brouard  7961:       else{
1.260     brouard  7962:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  7963:          if (agedc[i] < 2*AGESUP) {
                   7964:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   7965:            if(j==0) j=1;  /* Survives at least one month after exam */
                   7966:            else if(j<0){
                   7967:              nberr++;
1.359     brouard  7968:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around 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]);
1.227     brouard  7969:              j=1; /* Temporary Dangerous patch */
                   7970:              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);
1.359     brouard  7971:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around 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]);
1.227     brouard  7972:              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);
                   7973:            }
                   7974:            k=k+1;
                   7975:            if (j >= jmax){
                   7976:              jmax=j;
                   7977:              ijmax=i;
                   7978:            }
                   7979:            if (j <= jmin){
                   7980:              jmin=j;
                   7981:              ijmin=i;
                   7982:            }
                   7983:            sum=sum+j;
                   7984:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   7985:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   7986:          }
                   7987:        }
                   7988:        else{
                   7989:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  7990: /*       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  7991:                                        
1.227     brouard  7992:          k=k+1;
                   7993:          if (j >= jmax) {
                   7994:            jmax=j;
                   7995:            ijmax=i;
                   7996:          }
                   7997:          else if (j <= jmin){
                   7998:            jmin=j;
                   7999:            ijmin=i;
                   8000:          }
                   8001:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   8002:          /*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]);*/
                   8003:          if(j<0){
                   8004:            nberr++;
1.359     brouard  8005:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld (around 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]);
                   8006:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld (around 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]);
1.227     brouard  8007:          }
                   8008:          sum=sum+j;
                   8009:        }
                   8010:        jk= j/stepm;
                   8011:        jl= j -jk*stepm;
                   8012:        ju= j -(jk+1)*stepm;
                   8013:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   8014:          if(jl==0){
                   8015:            dh[mi][i]=jk;
                   8016:            bh[mi][i]=0;
                   8017:          }else{ /* We want a negative bias in order to only have interpolation ie
                   8018:                  * to avoid the price of an extra matrix product in likelihood */
                   8019:            dh[mi][i]=jk+1;
                   8020:            bh[mi][i]=ju;
                   8021:          }
                   8022:        }else{
                   8023:          if(jl <= -ju){
                   8024:            dh[mi][i]=jk;
                   8025:            bh[mi][i]=jl;       /* bias is positive if real duration
                   8026:                                 * is higher than the multiple of stepm and negative otherwise.
                   8027:                                 */
                   8028:          }
                   8029:          else{
                   8030:            dh[mi][i]=jk+1;
                   8031:            bh[mi][i]=ju;
                   8032:          }
                   8033:          if(dh[mi][i]==0){
                   8034:            dh[mi][i]=1; /* At least one step */
                   8035:            bh[mi][i]=ju; /* At least one step */
                   8036:            /*  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);*/
                   8037:          }
                   8038:        } /* end if mle */
1.126     brouard  8039:       }
                   8040:     } /* end wave */
                   8041:   }
                   8042:   jmean=sum/k;
                   8043:   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  8044:   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  8045: }
1.126     brouard  8046: 
                   8047: /*********** Tricode ****************************/
1.220     brouard  8048:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  8049:  {
                   8050:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   8051:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   8052:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   8053:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   8054:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   8055:     */
1.130     brouard  8056: 
1.242     brouard  8057:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   8058:    int modmaxcovj=0; /* Modality max of covariates j */
                   8059:    int cptcode=0; /* Modality max of covariates j */
                   8060:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  8061: 
                   8062: 
1.242     brouard  8063:    /* cptcoveff=0;  */
                   8064:    /* *cptcov=0; */
1.126     brouard  8065:  
1.242     brouard  8066:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  8067:    for (k=1; k <= maxncov; k++)
                   8068:      for(j=1; j<=2; j++)
                   8069:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  8070: 
1.242     brouard  8071:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  8072:    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  8073:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  8074:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  8075:      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  8076:        switch(Fixed[k]) {
                   8077:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  8078:         modmaxcovj=0;
                   8079:         modmincovj=0;
1.242     brouard  8080:         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  8081:           /* 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  8082:           ij=(int)(covar[Tvar[k]][i]);
                   8083:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   8084:            * If product of Vn*Vm, still boolean *:
                   8085:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   8086:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   8087:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   8088:              modality of the nth covariate of individual i. */
                   8089:           if (ij > modmaxcovj)
                   8090:             modmaxcovj=ij; 
                   8091:           else if (ij < modmincovj) 
                   8092:             modmincovj=ij; 
1.287     brouard  8093:           if (ij <0 || ij >1 ){
1.311     brouard  8094:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8095:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8096:             fflush(ficlog);
                   8097:             exit(1);
1.287     brouard  8098:           }
                   8099:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  8100:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   8101:             exit(1);
                   8102:           }else
                   8103:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   8104:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   8105:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   8106:           /* getting the maximum value of the modality of the covariate
                   8107:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   8108:              female ies 1, then modmaxcovj=1.
                   8109:           */
                   8110:         } /* end for loop on individuals i */
                   8111:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8112:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8113:         cptcode=modmaxcovj;
                   8114:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   8115:         /*for (i=0; i<=cptcode; i++) {*/
                   8116:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   8117:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8118:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8119:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   8120:             if( j != -1){
                   8121:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   8122:                                  covariate for which somebody answered excluding 
                   8123:                                  undefined. Usually 2: 0 and 1. */
                   8124:             }
                   8125:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   8126:                                     covariate for which somebody answered including 
                   8127:                                     undefined. Usually 3: -1, 0 and 1. */
                   8128:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   8129:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   8130:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  8131:                        
1.242     brouard  8132:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   8133:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   8134:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   8135:         /* modmincovj=3; modmaxcovj = 7; */
                   8136:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   8137:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   8138:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   8139:         /* nbcode[Tvar[j]][ij]=k; */
                   8140:         /* nbcode[Tvar[j]][1]=0; */
                   8141:         /* nbcode[Tvar[j]][2]=1; */
                   8142:         /* nbcode[Tvar[j]][3]=2; */
                   8143:         /* To be continued (not working yet). */
                   8144:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  8145: 
                   8146:         /* 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*/
                   8147:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   8148:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   8149:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   8150:         /*, could be restored in the future */
                   8151:         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  8152:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   8153:             break;
                   8154:           }
                   8155:           ij++;
1.287     brouard  8156:           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  8157:           cptcode = ij; /* New max modality for covar j */
                   8158:         } /* end of loop on modality i=-1 to 1 or more */
                   8159:         break;
                   8160:        case 1: /* Testing on varying covariate, could be simple and
                   8161:                * should look at waves or product of fixed *
                   8162:                * varying. No time to test -1, assuming 0 and 1 only */
                   8163:         ij=0;
                   8164:         for(i=0; i<=1;i++){
                   8165:           nbcode[Tvar[k]][++ij]=i;
                   8166:         }
                   8167:         break;
                   8168:        default:
                   8169:         break;
                   8170:        } /* end switch */
                   8171:      } /* end dummy test */
1.349     brouard  8172:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  8173:        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  8174:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   8175:           printf("Error k=%d \n",k);
                   8176:           exit(1);
                   8177:         }
1.311     brouard  8178:         if(isnan(covar[Tvar[k]][i])){
                   8179:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8180:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8181:           fflush(ficlog);
                   8182:           exit(1);
                   8183:          }
                   8184:        }
1.335     brouard  8185:      } /* end Quanti */
1.287     brouard  8186:    } /* 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  8187:   
                   8188:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   8189:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   8190:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   8191:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   8192:      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 */ 
                   8193:      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 */
                   8194:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   8195:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   8196:   
                   8197:    ij=0;
                   8198:    /* 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  8199:    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 */
                   8200:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  8201:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   8202:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  8203:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   8204:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   8205:        /* 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  8206:        /* If product not in single variable we don't print results */
                   8207:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  8208:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   8209:        /* k=       1    2   3     4       5       6      7       8        9  */
                   8210:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   8211:        /* ij            1    2                                            3  */  
                   8212:        /* Tvaraff[ij]=  4    3                                            1  */
                   8213:        /* Tmodelind[ij]=2    3                                            9  */
                   8214:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  8215:        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*/
                   8216:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   8217:        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 */
                   8218:        if(Fixed[k]!=0)
                   8219:         anyvaryingduminmodel=1;
                   8220:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   8221:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8222:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   8223:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   8224:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   8225:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8226:      } 
                   8227:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   8228:    /* ij--; */
                   8229:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  8230:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  8231:                * because they can be excluded from the model and real
                   8232:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   8233:    for(j=ij+1; j<= cptcovt; j++){
                   8234:      Tvaraff[j]=0;
                   8235:      Tmodelind[j]=0;
                   8236:    }
                   8237:    for(j=ntveff+1; j<= cptcovt; j++){
                   8238:      TmodelInvind[j]=0;
                   8239:    }
                   8240:    /* To be sorted */
                   8241:    ;
                   8242:  }
1.126     brouard  8243: 
1.145     brouard  8244: 
1.126     brouard  8245: /*********** Health Expectancies ****************/
                   8246: 
1.235     brouard  8247:  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  8248: 
                   8249: {
                   8250:   /* Health expectancies, no variances */
1.329     brouard  8251:   /* cij is the combination in the list of combination of dummy covariates */
                   8252:   /* strstart is a string of time at start of computing */
1.164     brouard  8253:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  8254:   int nhstepma, nstepma; /* Decreasing with age */
                   8255:   double age, agelim, hf;
                   8256:   double ***p3mat;
                   8257:   double eip;
                   8258: 
1.238     brouard  8259:   /* pstamp(ficreseij); */
1.126     brouard  8260:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   8261:   fprintf(ficreseij,"# Age");
                   8262:   for(i=1; i<=nlstate;i++){
                   8263:     for(j=1; j<=nlstate;j++){
                   8264:       fprintf(ficreseij," e%1d%1d ",i,j);
                   8265:     }
                   8266:     fprintf(ficreseij," e%1d. ",i);
                   8267:   }
                   8268:   fprintf(ficreseij,"\n");
                   8269: 
                   8270:   
                   8271:   if(estepm < stepm){
                   8272:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8273:   }
                   8274:   else  hstepm=estepm;   
                   8275:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8276:    * This is mainly to measure the difference between two models: for example
                   8277:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8278:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8279:    * progression in between and thus overestimating or underestimating according
                   8280:    * to the curvature of the survival function. If, for the same date, we 
                   8281:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8282:    * to compare the new estimate of Life expectancy with the same linear 
                   8283:    * hypothesis. A more precise result, taking into account a more precise
                   8284:    * curvature will be obtained if estepm is as small as stepm. */
                   8285: 
                   8286:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8287:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8288:      nhstepm is the number of hstepm from age to agelim 
                   8289:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  8290:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  8291:      and note for a fixed period like estepm months */
                   8292:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8293:      survival function given by stepm (the optimization length). Unfortunately it
                   8294:      means that if the survival funtion is printed only each two years of age and if
                   8295:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8296:      results. So we changed our mind and took the option of the best precision.
                   8297:   */
                   8298:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8299: 
                   8300:   agelim=AGESUP;
                   8301:   /* If stepm=6 months */
                   8302:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   8303:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   8304:     
                   8305: /* nhstepm age range expressed in number of stepm */
                   8306:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8307:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8308:   /* if (stepm >= YEARM) hstepm=1;*/
                   8309:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8310:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8311: 
                   8312:   for (age=bage; age<=fage; age ++){ 
                   8313:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8314:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8315:     /* if (stepm >= YEARM) hstepm=1;*/
                   8316:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   8317: 
                   8318:     /* If stepm=6 months */
                   8319:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8320:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  8321:     /* 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  8322:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  8323:     
                   8324:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8325:     
                   8326:     printf("%d|",(int)age);fflush(stdout);
                   8327:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8328:     
                   8329:     /* Computing expectancies */
                   8330:     for(i=1; i<=nlstate;i++)
                   8331:       for(j=1; j<=nlstate;j++)
                   8332:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8333:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   8334:          
                   8335:          /* 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]);*/
                   8336: 
                   8337:        }
                   8338: 
                   8339:     fprintf(ficreseij,"%3.0f",age );
                   8340:     for(i=1; i<=nlstate;i++){
                   8341:       eip=0;
                   8342:       for(j=1; j<=nlstate;j++){
                   8343:        eip +=eij[i][j][(int)age];
                   8344:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   8345:       }
                   8346:       fprintf(ficreseij,"%9.4f", eip );
                   8347:     }
                   8348:     fprintf(ficreseij,"\n");
                   8349:     
                   8350:   }
                   8351:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8352:   printf("\n");
                   8353:   fprintf(ficlog,"\n");
                   8354:   
                   8355: }
                   8356: 
1.235     brouard  8357:  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  8358: 
                   8359: {
                   8360:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  8361:      to initial status i, ei. .
1.126     brouard  8362:   */
1.336     brouard  8363:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  8364:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   8365:   int nhstepma, nstepma; /* Decreasing with age */
                   8366:   double age, agelim, hf;
                   8367:   double ***p3matp, ***p3matm, ***varhe;
                   8368:   double **dnewm,**doldm;
                   8369:   double *xp, *xm;
                   8370:   double **gp, **gm;
                   8371:   double ***gradg, ***trgradg;
                   8372:   int theta;
                   8373: 
                   8374:   double eip, vip;
                   8375: 
                   8376:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   8377:   xp=vector(1,npar);
                   8378:   xm=vector(1,npar);
                   8379:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   8380:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   8381:   
                   8382:   pstamp(ficresstdeij);
                   8383:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   8384:   fprintf(ficresstdeij,"# Age");
                   8385:   for(i=1; i<=nlstate;i++){
                   8386:     for(j=1; j<=nlstate;j++)
                   8387:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   8388:     fprintf(ficresstdeij," e%1d. ",i);
                   8389:   }
                   8390:   fprintf(ficresstdeij,"\n");
                   8391: 
                   8392:   pstamp(ficrescveij);
                   8393:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   8394:   fprintf(ficrescveij,"# Age");
                   8395:   for(i=1; i<=nlstate;i++)
                   8396:     for(j=1; j<=nlstate;j++){
                   8397:       cptj= (j-1)*nlstate+i;
                   8398:       for(i2=1; i2<=nlstate;i2++)
                   8399:        for(j2=1; j2<=nlstate;j2++){
                   8400:          cptj2= (j2-1)*nlstate+i2;
                   8401:          if(cptj2 <= cptj)
                   8402:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   8403:        }
                   8404:     }
                   8405:   fprintf(ficrescveij,"\n");
                   8406:   
                   8407:   if(estepm < stepm){
                   8408:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8409:   }
                   8410:   else  hstepm=estepm;   
                   8411:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8412:    * This is mainly to measure the difference between two models: for example
                   8413:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8414:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8415:    * progression in between and thus overestimating or underestimating according
                   8416:    * to the curvature of the survival function. If, for the same date, we 
                   8417:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8418:    * to compare the new estimate of Life expectancy with the same linear 
                   8419:    * hypothesis. A more precise result, taking into account a more precise
                   8420:    * curvature will be obtained if estepm is as small as stepm. */
                   8421: 
                   8422:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8423:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8424:      nhstepm is the number of hstepm from age to agelim 
                   8425:      nstepm is the number of stepm from age to agelin. 
                   8426:      Look at hpijx to understand the reason of that which relies in memory size
                   8427:      and note for a fixed period like estepm months */
                   8428:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8429:      survival function given by stepm (the optimization length). Unfortunately it
                   8430:      means that if the survival funtion is printed only each two years of age and if
                   8431:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8432:      results. So we changed our mind and took the option of the best precision.
                   8433:   */
                   8434:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8435: 
                   8436:   /* If stepm=6 months */
                   8437:   /* nhstepm age range expressed in number of stepm */
                   8438:   agelim=AGESUP;
                   8439:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   8440:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8441:   /* if (stepm >= YEARM) hstepm=1;*/
                   8442:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8443:   
                   8444:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8445:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8446:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   8447:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   8448:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   8449:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   8450: 
                   8451:   for (age=bage; age<=fage; age ++){ 
                   8452:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8453:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8454:     /* if (stepm >= YEARM) hstepm=1;*/
                   8455:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  8456:                
1.126     brouard  8457:     /* If stepm=6 months */
                   8458:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8459:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   8460:     
                   8461:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  8462:                
1.126     brouard  8463:     /* Computing  Variances of health expectancies */
                   8464:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   8465:        decrease memory allocation */
                   8466:     for(theta=1; theta <=npar; theta++){
                   8467:       for(i=1; i<=npar; i++){ 
1.222     brouard  8468:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8469:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  8470:       }
1.235     brouard  8471:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   8472:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  8473:                        
1.126     brouard  8474:       for(j=1; j<= nlstate; j++){
1.222     brouard  8475:        for(i=1; i<=nlstate; i++){
                   8476:          for(h=0; h<=nhstepm-1; h++){
                   8477:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   8478:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   8479:          }
                   8480:        }
1.126     brouard  8481:       }
1.218     brouard  8482:                        
1.126     brouard  8483:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  8484:        for(h=0; h<=nhstepm-1; h++){
                   8485:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   8486:        }
1.126     brouard  8487:     }/* End theta */
                   8488:     
                   8489:     
                   8490:     for(h=0; h<=nhstepm-1; h++)
                   8491:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  8492:        for(theta=1; theta <=npar; theta++)
                   8493:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  8494:     
1.218     brouard  8495:                
1.222     brouard  8496:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  8497:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  8498:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  8499:                
1.222     brouard  8500:     printf("%d|",(int)age);fflush(stdout);
                   8501:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8502:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  8503:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  8504:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   8505:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   8506:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   8507:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   8508:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  8509:       }
                   8510:     }
1.320     brouard  8511:     /* if((int)age ==50){ */
                   8512:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   8513:     /* } */
1.126     brouard  8514:     /* Computing expectancies */
1.235     brouard  8515:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  8516:     for(i=1; i<=nlstate;i++)
                   8517:       for(j=1; j<=nlstate;j++)
1.222     brouard  8518:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8519:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  8520:                                        
1.222     brouard  8521:          /* 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  8522:                                        
1.222     brouard  8523:        }
1.269     brouard  8524: 
                   8525:     /* Standard deviation of expectancies ij */                
1.126     brouard  8526:     fprintf(ficresstdeij,"%3.0f",age );
                   8527:     for(i=1; i<=nlstate;i++){
                   8528:       eip=0.;
                   8529:       vip=0.;
                   8530:       for(j=1; j<=nlstate;j++){
1.222     brouard  8531:        eip += eij[i][j][(int)age];
                   8532:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   8533:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   8534:        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  8535:       }
                   8536:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   8537:     }
                   8538:     fprintf(ficresstdeij,"\n");
1.218     brouard  8539:                
1.269     brouard  8540:     /* Variance of expectancies ij */          
1.126     brouard  8541:     fprintf(ficrescveij,"%3.0f",age );
                   8542:     for(i=1; i<=nlstate;i++)
                   8543:       for(j=1; j<=nlstate;j++){
1.222     brouard  8544:        cptj= (j-1)*nlstate+i;
                   8545:        for(i2=1; i2<=nlstate;i2++)
                   8546:          for(j2=1; j2<=nlstate;j2++){
                   8547:            cptj2= (j2-1)*nlstate+i2;
                   8548:            if(cptj2 <= cptj)
                   8549:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   8550:          }
1.126     brouard  8551:       }
                   8552:     fprintf(ficrescveij,"\n");
1.218     brouard  8553:                
1.126     brouard  8554:   }
                   8555:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   8556:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   8557:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   8558:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   8559:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8560:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8561:   printf("\n");
                   8562:   fprintf(ficlog,"\n");
1.218     brouard  8563:        
1.126     brouard  8564:   free_vector(xm,1,npar);
                   8565:   free_vector(xp,1,npar);
                   8566:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   8567:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   8568:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   8569: }
1.218     brouard  8570:  
1.126     brouard  8571: /************ Variance ******************/
1.235     brouard  8572:  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  8573:  {
1.361   ! brouard  8574:    /** Computes the matrix of variance covariance of health expectancies e.j= sum_i w_i e_ij where w_i depends of popbased,
        !          8575:     * either cross-sectional or implied.
        !          8576:     * return vareij[i][j][(int)age]=cov(e.i,e.j)=sum_h sum_k trgrad(h_p.i) V(theta) grad(k_p.k) Equation 20
1.279     brouard  8577:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   8578:     * double **newm;
                   8579:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   8580:     */
1.218     brouard  8581:   
                   8582:    /* int movingaverage(); */
                   8583:    double **dnewm,**doldm;
                   8584:    double **dnewmp,**doldmp;
                   8585:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  8586:    int first=0;
1.218     brouard  8587:    int k;
                   8588:    double *xp;
1.279     brouard  8589:    double **gp, **gm;  /**< for var eij */
                   8590:    double ***gradg, ***trgradg; /**< for var eij */
                   8591:    double **gradgp, **trgradgp; /**< for var p point j */
                   8592:    double *gpp, *gmp; /**< for var p point j */
1.361   ! brouard  8593:    double **varppt; /**< for var e.. nlstate+1 to nlstate+ndeath */
1.218     brouard  8594:    double ***p3mat;
                   8595:    double age,agelim, hf;
                   8596:    /* double ***mobaverage; */
                   8597:    int theta;
                   8598:    char digit[4];
                   8599:    char digitp[25];
                   8600: 
                   8601:    char fileresprobmorprev[FILENAMELENGTH];
                   8602: 
                   8603:    if(popbased==1){
                   8604:      if(mobilav!=0)
                   8605:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   8606:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   8607:    }
                   8608:    else 
                   8609:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  8610: 
1.218     brouard  8611:    /* if (mobilav!=0) { */
                   8612:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8613:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   8614:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   8615:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   8616:    /*   } */
                   8617:    /* } */
                   8618: 
                   8619:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   8620:    sprintf(digit,"%-d",ij);
                   8621:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   8622:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   8623:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   8624:    strcat(fileresprobmorprev,fileresu);
                   8625:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   8626:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   8627:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   8628:    }
                   8629:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8630:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8631:    pstamp(ficresprobmorprev);
                   8632:    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  8633:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  8634: 
                   8635:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   8636:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   8637:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   8638:    /* } */
                   8639:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  8640:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  8641:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  8642:    }
1.337     brouard  8643:    /* for(j=1;j<=cptcoveff;j++)  */
                   8644:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  8645:    fprintf(ficresprobmorprev,"\n");
                   8646: 
1.218     brouard  8647:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   8648:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   8649:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   8650:      for(i=1; i<=nlstate;i++)
                   8651:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   8652:    }  
                   8653:    fprintf(ficresprobmorprev,"\n");
                   8654:   
                   8655:    fprintf(ficgp,"\n# Routine varevsij");
                   8656:    fprintf(ficgp,"\nunset title \n");
                   8657:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   8658:    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");
                   8659:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  8660: 
1.361   ! brouard  8661:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); /* In fact, currently a double */
1.218     brouard  8662:    pstamp(ficresvij);
                   8663:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   8664:    if(popbased==1)
                   8665:      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);
                   8666:    else
                   8667:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   8668:    fprintf(ficresvij,"# Age");
                   8669:    for(i=1; i<=nlstate;i++)
                   8670:      for(j=1; j<=nlstate;j++)
                   8671:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   8672:    fprintf(ficresvij,"\n");
                   8673: 
                   8674:    xp=vector(1,npar);
                   8675:    dnewm=matrix(1,nlstate,1,npar);
                   8676:    doldm=matrix(1,nlstate,1,nlstate);
                   8677:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   8678:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8679: 
                   8680:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   8681:    gpp=vector(nlstate+1,nlstate+ndeath);
                   8682:    gmp=vector(nlstate+1,nlstate+ndeath);
                   8683:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  8684:   
1.218     brouard  8685:    if(estepm < stepm){
                   8686:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   8687:    }
                   8688:    else  hstepm=estepm;   
                   8689:    /* For example we decided to compute the life expectancy with the smallest unit */
                   8690:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8691:       nhstepm is the number of hstepm from age to agelim 
                   8692:       nstepm is the number of stepm from age to agelim. 
                   8693:       Look at function hpijx to understand why because of memory size limitations, 
                   8694:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   8695:       survival function given by stepm (the optimization length). Unfortunately it
                   8696:       means that if the survival funtion is printed every two years of age and if
                   8697:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8698:       results. So we changed our mind and took the option of the best precision.
                   8699:    */
                   8700:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8701:    agelim = AGESUP;
                   8702:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8703:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8704:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8705:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8706:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   8707:      gp=matrix(0,nhstepm,1,nlstate);
                   8708:      gm=matrix(0,nhstepm,1,nlstate);
                   8709:                
                   8710:                
                   8711:      for(theta=1; theta <=npar; theta++){
                   8712:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   8713:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8714:        }
1.279     brouard  8715:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   8716:        * returns into prlim .
1.288     brouard  8717:        */
1.242     brouard  8718:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  8719: 
                   8720:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  8721:        if (popbased==1) {
                   8722:         if(mobilav ==0){
                   8723:           for(i=1; i<=nlstate;i++)
                   8724:             prlim[i][i]=probs[(int)age][i][ij];
                   8725:         }else{ /* mobilav */ 
                   8726:           for(i=1; i<=nlstate;i++)
                   8727:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8728:         }
                   8729:        }
1.361   ! brouard  8730:        /**< Computes the shifted plus (gp) transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  8731:        */                      
                   8732:        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  8733:        /**< 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  8734:        * at horizon h in state j including mortality.
                   8735:        */
1.218     brouard  8736:        for(j=1; j<= nlstate; j++){
                   8737:         for(h=0; h<=nhstepm; h++){
                   8738:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
1.361   ! brouard  8739:             gp[h][j] += prlim[i][i]*p3mat[i][j][h]; /* gp[h][j]= w_i h_pij */
1.218     brouard  8740:         }
                   8741:        }
1.279     brouard  8742:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  8743:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  8744:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  8745:        */
1.361   ! brouard  8746:        for(j=nlstate+1;j<=nlstate+ndeath;j++){ /* Currently only once for theta plus  p.3(age) Sum_i wi pi3*/
1.218     brouard  8747:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   8748:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  8749:        }
                   8750:        
                   8751:        /* Again with minus shift */
1.218     brouard  8752:                        
                   8753:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   8754:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8755: 
1.242     brouard  8756:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  8757:                        
                   8758:        if (popbased==1) {
                   8759:         if(mobilav ==0){
                   8760:           for(i=1; i<=nlstate;i++)
                   8761:             prlim[i][i]=probs[(int)age][i][ij];
                   8762:         }else{ /* mobilav */ 
                   8763:           for(i=1; i<=nlstate;i++)
                   8764:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8765:         }
                   8766:        }
                   8767:                        
1.361   ! brouard  8768:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Still minus */
1.218     brouard  8769:                        
1.361   ! brouard  8770:        for(j=1; j<= nlstate; j++){  /* gm[h][j]= Sum_i of wi * pij =  h_p.j */
1.218     brouard  8771:         for(h=0; h<=nhstepm; h++){
                   8772:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   8773:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   8774:         }
                   8775:        }
                   8776:        /* This for computing probability of death (h=1 means
                   8777:          computed over hstepm matrices product = hstepm*stepm months) 
1.361   ! brouard  8778:          as a weighted average of prlim. j is death. gmp[3]=sum_i w_i*p_i3=p.3 minus theta
1.218     brouard  8779:        */
1.361   ! brouard  8780:        for(j=nlstate+1;j<=nlstate+ndeath;j++){  /* Currently only once theta_minus  p.3=Sum_i wi pi3*/
1.218     brouard  8781:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   8782:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   8783:        }    
1.279     brouard  8784:        /* end shifting computations */
                   8785: 
1.361   ! brouard  8786:        /**< Computing gradient of p.j matrix at horizon h and still for one parameter of vector theta
        !          8787:        * equation 31 and 32
1.279     brouard  8788:        */
1.361   ! brouard  8789:        for(j=1; j<= nlstate; j++) /* computes grad p.j(x, over each  h) where p.j is Sum_i w_i*pij(x over h)
        !          8790:                                  * equation 24 */
1.218     brouard  8791:         for(h=0; h<=nhstepm; h++){
                   8792:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   8793:         }
1.361   ! brouard  8794:        /**< Gradient of overall mortality p.3 (or p.death) 
1.279     brouard  8795:        */
1.361   ! brouard  8796:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* computes grad of p.3 from wi+pi3 grad p.3 (theta) */
1.218     brouard  8797:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   8798:        }
                   8799:                        
                   8800:      } /* End theta */
1.279     brouard  8801:      
1.361   ! brouard  8802:      /* We got the gradient matrix for each theta and each state j of gradg(h]theta][j)=grad(_hp.j(theta) */           
        !          8803:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
1.218     brouard  8804:                
1.361   ! brouard  8805:      for(h=0; h<=nhstepm; h++) /* veij */ /* computes the transposed of grad  (_hp.j(theta)*/
1.218     brouard  8806:        for(j=1; j<=nlstate;j++)
                   8807:         for(theta=1; theta <=npar; theta++)
                   8808:           trgradg[h][j][theta]=gradg[h][theta][j];
                   8809:                
1.361   ! brouard  8810:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* computes transposed of grad p.3 (theta)*/
1.218     brouard  8811:        for(theta=1; theta <=npar; theta++)
                   8812:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  8813:      /**< as well as its transposed matrix 
                   8814:       */               
1.218     brouard  8815:                
                   8816:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8817:      for(i=1;i<=nlstate;i++)
                   8818:        for(j=1;j<=nlstate;j++)
                   8819:         vareij[i][j][(int)age] =0.;
1.279     brouard  8820: 
                   8821:      /* Computing trgradg by matcov by gradg at age and summing over h
1.361   ! brouard  8822:       * and k (nhstepm) formula 32 of article
        !          8823:       * Lievre-Brouard-Heathcote so that for each j, computes the cov(e.j,e.k) (formula 31).
        !          8824:       * for given h and k computes trgradg[h](i,j) matcov (theta) gradg(k)(i,j) into vareij[i][j] which is
        !          8825:       cov(e.i,e.j) and sums on h and k
        !          8826:       * including the covariances.
1.279     brouard  8827:       */
                   8828:      
1.218     brouard  8829:      for(h=0;h<=nhstepm;h++){
                   8830:        for(k=0;k<=nhstepm;k++){
                   8831:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   8832:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   8833:         for(i=1;i<=nlstate;i++)
                   8834:           for(j=1;j<=nlstate;j++)
1.361   ! brouard  8835:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf; /* This is vareij=sum_h sum_k trgrad(h_pij) V(theta) grad(k_pij)
        !          8836:                                                             including the covariances of e.j */
1.218     brouard  8837:        }
                   8838:      }
                   8839:                
1.361   ! brouard  8840:      /* Mortality: pptj is p.3 or p.death = trgradgp by cov by gradgp, variance of
        !          8841:       * p.3=1-p..=1-sum i p.i  overall mortality computed directly because
1.279     brouard  8842:       * we compute the grad (wix pijx) instead of grad (pijx),even if
1.361   ! brouard  8843:       * wix is independent of theta. 
1.279     brouard  8844:       */
1.218     brouard  8845:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   8846:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   8847:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   8848:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
1.361   ! brouard  8849:         varppt[j][i]=doldmp[j][i];  /* This is the variance of p.3 */
1.218     brouard  8850:      /* end ppptj */
                   8851:      /*  x centered again */
                   8852:                
1.242     brouard  8853:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  8854:                
                   8855:      if (popbased==1) {
                   8856:        if(mobilav ==0){
                   8857:         for(i=1; i<=nlstate;i++)
                   8858:           prlim[i][i]=probs[(int)age][i][ij];
                   8859:        }else{ /* mobilav */ 
                   8860:         for(i=1; i<=nlstate;i++)
                   8861:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   8862:        }
                   8863:      }
                   8864:                
                   8865:      /* This for computing probability of death (h=1 means
                   8866:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   8867:        as a weighted average of prlim.
                   8868:      */
1.235     brouard  8869:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  8870:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8871:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
1.361   ! brouard  8872:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; /* gmp[j] is p.3 */
1.218     brouard  8873:      }    
                   8874:      /* end probability of death */
                   8875:                
                   8876:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   8877:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
1.361   ! brouard  8878:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));/* p.3 (STD p.3) */
1.218     brouard  8879:        for(i=1; i<=nlstate;i++){
1.361   ! brouard  8880:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]); /* wi, pi3 */
1.218     brouard  8881:        }
                   8882:      } 
                   8883:      fprintf(ficresprobmorprev,"\n");
                   8884:                
                   8885:      fprintf(ficresvij,"%.0f ",age );
                   8886:      for(i=1; i<=nlstate;i++)
                   8887:        for(j=1; j<=nlstate;j++){
                   8888:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   8889:        }
                   8890:      fprintf(ficresvij,"\n");
                   8891:      free_matrix(gp,0,nhstepm,1,nlstate);
                   8892:      free_matrix(gm,0,nhstepm,1,nlstate);
                   8893:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   8894:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   8895:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8896:    } /* End age */
                   8897:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   8898:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   8899:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   8900:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   8901:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   8902:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   8903:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   8904:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   8905:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   8906:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   8907:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8908:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8909:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   8910:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   8911:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   8912:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   8913:    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);
                   8914:    /*  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  8915:     */
1.218     brouard  8916:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   8917:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  8918: 
1.218     brouard  8919:    free_vector(xp,1,npar);
                   8920:    free_matrix(doldm,1,nlstate,1,nlstate);
                   8921:    free_matrix(dnewm,1,nlstate,1,npar);
                   8922:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8923:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   8924:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8925:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8926:    fclose(ficresprobmorprev);
                   8927:    fflush(ficgp);
                   8928:    fflush(fichtm); 
                   8929:  }  /* end varevsij */
1.126     brouard  8930: 
                   8931: /************ Variance of prevlim ******************/
1.269     brouard  8932:  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  8933: {
1.205     brouard  8934:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  8935:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  8936: 
1.268     brouard  8937:   double **dnewmpar,**doldm;
1.126     brouard  8938:   int i, j, nhstepm, hstepm;
                   8939:   double *xp;
                   8940:   double *gp, *gm;
                   8941:   double **gradg, **trgradg;
1.208     brouard  8942:   double **mgm, **mgp;
1.126     brouard  8943:   double age,agelim;
                   8944:   int theta;
                   8945:   
                   8946:   pstamp(ficresvpl);
1.288     brouard  8947:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  8948:   fprintf(ficresvpl,"# Age ");
                   8949:   if(nresult >=1)
                   8950:     fprintf(ficresvpl," Result# ");
1.126     brouard  8951:   for(i=1; i<=nlstate;i++)
                   8952:       fprintf(ficresvpl," %1d-%1d",i,i);
                   8953:   fprintf(ficresvpl,"\n");
                   8954: 
                   8955:   xp=vector(1,npar);
1.268     brouard  8956:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  8957:   doldm=matrix(1,nlstate,1,nlstate);
                   8958:   
                   8959:   hstepm=1*YEARM; /* Every year of age */
                   8960:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   8961:   agelim = AGESUP;
                   8962:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8963:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8964:     if (stepm >= YEARM) hstepm=1;
                   8965:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8966:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  8967:     mgp=matrix(1,npar,1,nlstate);
                   8968:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  8969:     gp=vector(1,nlstate);
                   8970:     gm=vector(1,nlstate);
                   8971: 
                   8972:     for(theta=1; theta <=npar; theta++){
                   8973:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   8974:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8975:       }
1.288     brouard  8976:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   8977:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   8978:       /* else */
                   8979:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  8980:       for(i=1;i<=nlstate;i++){
1.126     brouard  8981:        gp[i] = prlim[i][i];
1.208     brouard  8982:        mgp[theta][i] = prlim[i][i];
                   8983:       }
1.126     brouard  8984:       for(i=1; i<=npar; i++) /* Computes gradient */
                   8985:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8986:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   8987:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   8988:       /* else */
                   8989:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  8990:       for(i=1;i<=nlstate;i++){
1.126     brouard  8991:        gm[i] = prlim[i][i];
1.208     brouard  8992:        mgm[theta][i] = prlim[i][i];
                   8993:       }
1.126     brouard  8994:       for(i=1;i<=nlstate;i++)
                   8995:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  8996:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  8997:     } /* End theta */
                   8998: 
                   8999:     trgradg =matrix(1,nlstate,1,npar);
                   9000: 
                   9001:     for(j=1; j<=nlstate;j++)
                   9002:       for(theta=1; theta <=npar; theta++)
                   9003:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  9004:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9005:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9006:     /*   for(j=1; j<=nlstate;j++){ */
                   9007:     /*         printf(" %d ",j); */
                   9008:     /*         for(theta=1; theta <=npar; theta++) */
                   9009:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9010:     /*         printf("\n "); */
                   9011:     /*   } */
                   9012:     /* } */
                   9013:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9014:     /*   printf("\n gradg %d ",(int)age); */
                   9015:     /*   for(j=1; j<=nlstate;j++){ */
                   9016:     /*         printf("%d ",j); */
                   9017:     /*         for(theta=1; theta <=npar; theta++) */
                   9018:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9019:     /*         printf("\n "); */
                   9020:     /*   } */
                   9021:     /* } */
1.126     brouard  9022: 
                   9023:     for(i=1;i<=nlstate;i++)
                   9024:       varpl[i][(int)age] =0.;
1.209     brouard  9025:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  9026:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9027:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9028:     }else{
1.268     brouard  9029:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9030:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9031:     }
1.126     brouard  9032:     for(i=1;i<=nlstate;i++)
                   9033:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9034: 
                   9035:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  9036:     if(nresult >=1)
                   9037:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  9038:     for(i=1; i<=nlstate;i++){
1.126     brouard  9039:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  9040:       /* for(j=1;j<=nlstate;j++) */
                   9041:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   9042:     }
1.126     brouard  9043:     fprintf(ficresvpl,"\n");
                   9044:     free_vector(gp,1,nlstate);
                   9045:     free_vector(gm,1,nlstate);
1.208     brouard  9046:     free_matrix(mgm,1,npar,1,nlstate);
                   9047:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  9048:     free_matrix(gradg,1,npar,1,nlstate);
                   9049:     free_matrix(trgradg,1,nlstate,1,npar);
                   9050:   } /* End age */
                   9051: 
                   9052:   free_vector(xp,1,npar);
                   9053:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  9054:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   9055: 
                   9056: }
                   9057: 
                   9058: 
                   9059: /************ Variance of backprevalence limit ******************/
1.269     brouard  9060:  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  9061: {
                   9062:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   9063:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   9064: 
                   9065:   double **dnewmpar,**doldm;
                   9066:   int i, j, nhstepm, hstepm;
                   9067:   double *xp;
                   9068:   double *gp, *gm;
                   9069:   double **gradg, **trgradg;
                   9070:   double **mgm, **mgp;
                   9071:   double age,agelim;
                   9072:   int theta;
                   9073:   
                   9074:   pstamp(ficresvbl);
                   9075:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   9076:   fprintf(ficresvbl,"# Age ");
                   9077:   if(nresult >=1)
                   9078:     fprintf(ficresvbl," Result# ");
                   9079:   for(i=1; i<=nlstate;i++)
                   9080:       fprintf(ficresvbl," %1d-%1d",i,i);
                   9081:   fprintf(ficresvbl,"\n");
                   9082: 
                   9083:   xp=vector(1,npar);
                   9084:   dnewmpar=matrix(1,nlstate,1,npar);
                   9085:   doldm=matrix(1,nlstate,1,nlstate);
                   9086:   
                   9087:   hstepm=1*YEARM; /* Every year of age */
                   9088:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   9089:   agelim = AGEINF;
                   9090:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   9091:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9092:     if (stepm >= YEARM) hstepm=1;
                   9093:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9094:     gradg=matrix(1,npar,1,nlstate);
                   9095:     mgp=matrix(1,npar,1,nlstate);
                   9096:     mgm=matrix(1,npar,1,nlstate);
                   9097:     gp=vector(1,nlstate);
                   9098:     gm=vector(1,nlstate);
                   9099: 
                   9100:     for(theta=1; theta <=npar; theta++){
                   9101:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9102:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9103:       }
                   9104:       if(mobilavproj > 0 )
                   9105:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9106:       else
                   9107:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9108:       for(i=1;i<=nlstate;i++){
                   9109:        gp[i] = bprlim[i][i];
                   9110:        mgp[theta][i] = bprlim[i][i];
                   9111:       }
                   9112:      for(i=1; i<=npar; i++) /* Computes gradient */
                   9113:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   9114:        if(mobilavproj > 0 )
                   9115:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9116:        else
                   9117:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9118:       for(i=1;i<=nlstate;i++){
                   9119:        gm[i] = bprlim[i][i];
                   9120:        mgm[theta][i] = bprlim[i][i];
                   9121:       }
                   9122:       for(i=1;i<=nlstate;i++)
                   9123:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   9124:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   9125:     } /* End theta */
                   9126: 
                   9127:     trgradg =matrix(1,nlstate,1,npar);
                   9128: 
                   9129:     for(j=1; j<=nlstate;j++)
                   9130:       for(theta=1; theta <=npar; theta++)
                   9131:        trgradg[j][theta]=gradg[theta][j];
                   9132:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9133:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9134:     /*   for(j=1; j<=nlstate;j++){ */
                   9135:     /*         printf(" %d ",j); */
                   9136:     /*         for(theta=1; theta <=npar; theta++) */
                   9137:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9138:     /*         printf("\n "); */
                   9139:     /*   } */
                   9140:     /* } */
                   9141:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9142:     /*   printf("\n gradg %d ",(int)age); */
                   9143:     /*   for(j=1; j<=nlstate;j++){ */
                   9144:     /*         printf("%d ",j); */
                   9145:     /*         for(theta=1; theta <=npar; theta++) */
                   9146:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9147:     /*         printf("\n "); */
                   9148:     /*   } */
                   9149:     /* } */
                   9150: 
                   9151:     for(i=1;i<=nlstate;i++)
                   9152:       varbpl[i][(int)age] =0.;
                   9153:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   9154:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9155:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9156:     }else{
                   9157:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9158:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9159:     }
                   9160:     for(i=1;i<=nlstate;i++)
                   9161:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9162: 
                   9163:     fprintf(ficresvbl,"%.0f ",age );
                   9164:     if(nresult >=1)
                   9165:       fprintf(ficresvbl,"%d ",nres );
                   9166:     for(i=1; i<=nlstate;i++)
                   9167:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   9168:     fprintf(ficresvbl,"\n");
                   9169:     free_vector(gp,1,nlstate);
                   9170:     free_vector(gm,1,nlstate);
                   9171:     free_matrix(mgm,1,npar,1,nlstate);
                   9172:     free_matrix(mgp,1,npar,1,nlstate);
                   9173:     free_matrix(gradg,1,npar,1,nlstate);
                   9174:     free_matrix(trgradg,1,nlstate,1,npar);
                   9175:   } /* End age */
                   9176: 
                   9177:   free_vector(xp,1,npar);
                   9178:   free_matrix(doldm,1,nlstate,1,npar);
                   9179:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  9180: 
                   9181: }
                   9182: 
                   9183: /************ Variance of one-step probabilities  ******************/
                   9184: 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  9185:  {
                   9186:    int i, j=0,  k1, l1, tj;
                   9187:    int k2, l2, j1,  z1;
                   9188:    int k=0, l;
                   9189:    int first=1, first1, first2;
1.326     brouard  9190:    int nres=0; /* New */
1.222     brouard  9191:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   9192:    double **dnewm,**doldm;
                   9193:    double *xp;
                   9194:    double *gp, *gm;
                   9195:    double **gradg, **trgradg;
                   9196:    double **mu;
                   9197:    double age, cov[NCOVMAX+1];
                   9198:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   9199:    int theta;
                   9200:    char fileresprob[FILENAMELENGTH];
                   9201:    char fileresprobcov[FILENAMELENGTH];
                   9202:    char fileresprobcor[FILENAMELENGTH];
                   9203:    double ***varpij;
                   9204: 
                   9205:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  9206:    strcat(fileresprob,fileresu);
1.222     brouard  9207:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   9208:      printf("Problem with resultfile: %s\n", fileresprob);
                   9209:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   9210:    }
                   9211:    strcpy(fileresprobcov,"PROBCOV_"); 
                   9212:    strcat(fileresprobcov,fileresu);
                   9213:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   9214:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   9215:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   9216:    }
                   9217:    strcpy(fileresprobcor,"PROBCOR_"); 
                   9218:    strcat(fileresprobcor,fileresu);
                   9219:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   9220:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   9221:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   9222:    }
                   9223:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9224:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9225:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9226:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9227:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9228:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9229:    pstamp(ficresprob);
                   9230:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   9231:    fprintf(ficresprob,"# Age");
                   9232:    pstamp(ficresprobcov);
                   9233:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   9234:    fprintf(ficresprobcov,"# Age");
                   9235:    pstamp(ficresprobcor);
                   9236:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   9237:    fprintf(ficresprobcor,"# Age");
1.126     brouard  9238: 
                   9239: 
1.222     brouard  9240:    for(i=1; i<=nlstate;i++)
                   9241:      for(j=1; j<=(nlstate+ndeath);j++){
                   9242:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   9243:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   9244:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   9245:      }  
                   9246:    /* fprintf(ficresprob,"\n");
                   9247:       fprintf(ficresprobcov,"\n");
                   9248:       fprintf(ficresprobcor,"\n");
                   9249:    */
                   9250:    xp=vector(1,npar);
                   9251:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9252:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9253:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   9254:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   9255:    first=1;
                   9256:    fprintf(ficgp,"\n# Routine varprob");
                   9257:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   9258:    fprintf(fichtm,"\n");
                   9259: 
1.288     brouard  9260:    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  9261:    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);
                   9262:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  9263: and drawn. It helps understanding how is the covariance between two incidences.\
                   9264:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  9265:    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  9266: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   9267: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   9268: standard deviations wide on each axis. <br>\
                   9269:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   9270:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   9271: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   9272: 
1.222     brouard  9273:    cov[1]=1;
                   9274:    /* tj=cptcoveff; */
1.225     brouard  9275:    tj = (int) pow(2,cptcoveff);
1.222     brouard  9276:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   9277:    j1=0;
1.332     brouard  9278: 
                   9279:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   9280:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  9281:      /* 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  9282:      if(tj != 1 && TKresult[nres]!= j1)
                   9283:        continue;
                   9284: 
                   9285:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   9286:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   9287:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  9288:      if  (cptcovn>0) {
1.334     brouard  9289:        fprintf(ficresprob, "\n#********** Variable ");
                   9290:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   9291:        fprintf(ficgp, "\n#********** Variable ");
                   9292:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   9293:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   9294: 
                   9295:        /* Including quantitative variables of the resultline to be done */
                   9296:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  9297:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  9298:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   9299:         /* 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  9300:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   9301:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   9302:             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  */
                   9303:             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  */
                   9304:             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  */
                   9305:             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  */
                   9306:             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  */
                   9307:             fprintf(ficresprob,"fixed ");
                   9308:             fprintf(ficresprobcov,"fixed ");
                   9309:             fprintf(ficgp,"fixed ");
                   9310:             fprintf(fichtmcov,"fixed ");
                   9311:             fprintf(ficresprobcor,"fixed ");
                   9312:           }else{
                   9313:             fprintf(ficresprob,"varyi ");
                   9314:             fprintf(ficresprobcov,"varyi ");
                   9315:             fprintf(ficgp,"varyi ");
                   9316:             fprintf(fichtmcov,"varyi ");
                   9317:             fprintf(ficresprobcor,"varyi ");
                   9318:           }
                   9319:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   9320:           /* For each selected (single) quantitative value */
1.337     brouard  9321:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  9322:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   9323:             fprintf(ficresprob,"fixed ");
                   9324:             fprintf(ficresprobcov,"fixed ");
                   9325:             fprintf(ficgp,"fixed ");
                   9326:             fprintf(fichtmcov,"fixed ");
                   9327:             fprintf(ficresprobcor,"fixed ");
                   9328:           }else{
                   9329:             fprintf(ficresprob,"varyi ");
                   9330:             fprintf(ficresprobcov,"varyi ");
                   9331:             fprintf(ficgp,"varyi ");
                   9332:             fprintf(fichtmcov,"varyi ");
                   9333:             fprintf(ficresprobcor,"varyi ");
                   9334:           }
                   9335:         }else{
                   9336:           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 */
                   9337:           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 */
                   9338:           exit(1);
                   9339:         }
                   9340:        } /* End loop on variable of this resultline */
                   9341:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  9342:        fprintf(ficresprob, "**********\n#\n");
                   9343:        fprintf(ficresprobcov, "**********\n#\n");
                   9344:        fprintf(ficgp, "**********\n#\n");
                   9345:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   9346:        fprintf(ficresprobcor, "**********\n#");    
                   9347:        if(invalidvarcomb[j1]){
                   9348:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   9349:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   9350:         continue;
                   9351:        }
                   9352:      }
                   9353:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   9354:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9355:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   9356:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  9357:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  9358:        cov[2]=age;
                   9359:        if(nagesqr==1)
                   9360:         cov[3]= age*age;
1.334     brouard  9361:        /* New code end of combination but for each resultline */
                   9362:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  9363:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  9364:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  9365:         }else{
1.334     brouard  9366:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  9367:         }
1.334     brouard  9368:        }/* End of loop on model equation */
                   9369: /* Old code */
                   9370:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   9371:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   9372:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   9373:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   9374:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   9375:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   9376:        /*                                                                  * 1  1 1 1 1 */
                   9377:        /*                                                                  * 2  2 1 1 1 */
                   9378:        /*                                                                  * 3  1 2 1 1 */
                   9379:        /*                                                                  *\/ */
                   9380:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   9381:        /* } */
                   9382:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   9383:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   9384:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   9385:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   9386:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   9387:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   9388:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9389:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   9390:        /*         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]); */
                   9391:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   9392:        /*         /\* exit(1); *\/ */
                   9393:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   9394:        /*       } */
                   9395:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9396:        /* } */
                   9397:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   9398:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   9399:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9400:        /*           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]])]; */
                   9401:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9402:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   9403:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   9404:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   9405:        /*         } */
                   9406:        /*       }else{ */
                   9407:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9408:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   9409:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   9410:        /*         }else{ */
                   9411:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   9412:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   9413:        /*         } */
                   9414:        /*       } */
                   9415:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9416:        /* } */                 
1.326     brouard  9417: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  9418:        for(theta=1; theta <=npar; theta++){
                   9419:         for(i=1; i<=npar; i++)
                   9420:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  9421:                                
1.222     brouard  9422:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  9423:                                
1.222     brouard  9424:         k=0;
                   9425:         for(i=1; i<= (nlstate); i++){
                   9426:           for(j=1; j<=(nlstate+ndeath);j++){
                   9427:             k=k+1;
                   9428:             gp[k]=pmmij[i][j];
                   9429:           }
                   9430:         }
1.220     brouard  9431:                                
1.222     brouard  9432:         for(i=1; i<=npar; i++)
                   9433:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  9434:                                
1.222     brouard  9435:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   9436:         k=0;
                   9437:         for(i=1; i<=(nlstate); i++){
                   9438:           for(j=1; j<=(nlstate+ndeath);j++){
                   9439:             k=k+1;
                   9440:             gm[k]=pmmij[i][j];
                   9441:           }
                   9442:         }
1.220     brouard  9443:                                
1.222     brouard  9444:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   9445:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   9446:        }
1.126     brouard  9447: 
1.222     brouard  9448:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   9449:         for(theta=1; theta <=npar; theta++)
                   9450:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  9451:                        
1.222     brouard  9452:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   9453:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  9454:                        
1.222     brouard  9455:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  9456:                        
1.222     brouard  9457:        k=0;
                   9458:        for(i=1; i<=(nlstate); i++){
                   9459:         for(j=1; j<=(nlstate+ndeath);j++){
                   9460:           k=k+1;
                   9461:           mu[k][(int) age]=pmmij[i][j];
                   9462:         }
                   9463:        }
                   9464:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   9465:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   9466:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  9467:                        
1.222     brouard  9468:        /*printf("\n%d ",(int)age);
                   9469:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9470:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9471:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9472:         }*/
1.220     brouard  9473:                        
1.222     brouard  9474:        fprintf(ficresprob,"\n%d ",(int)age);
                   9475:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   9476:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  9477:                        
1.222     brouard  9478:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   9479:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   9480:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9481:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   9482:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   9483:        }
                   9484:        i=0;
                   9485:        for (k=1; k<=(nlstate);k++){
                   9486:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   9487:           i++;
                   9488:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   9489:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   9490:           for (j=1; j<=i;j++){
                   9491:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   9492:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   9493:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   9494:           }
                   9495:         }
                   9496:        }/* end of loop for state */
                   9497:      } /* end of loop for age */
                   9498:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9499:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9500:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9501:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9502:     
                   9503:      /* Confidence intervalle of pij  */
                   9504:      /*
                   9505:        fprintf(ficgp,"\nunset parametric;unset label");
                   9506:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   9507:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   9508:        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);
                   9509:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   9510:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   9511:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   9512:      */
                   9513:                
                   9514:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   9515:      first1=1;first2=2;
                   9516:      for (k2=1; k2<=(nlstate);k2++){
                   9517:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   9518:         if(l2==k2) continue;
                   9519:         j=(k2-1)*(nlstate+ndeath)+l2;
                   9520:         for (k1=1; k1<=(nlstate);k1++){
                   9521:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   9522:             if(l1==k1) continue;
                   9523:             i=(k1-1)*(nlstate+ndeath)+l1;
                   9524:             if(i<=j) continue;
                   9525:             for (age=bage; age<=fage; age ++){ 
                   9526:               if ((int)age %5==0){
                   9527:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   9528:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9529:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9530:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   9531:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   9532:                 c12=cv12/sqrt(v1*v2);
                   9533:                 /* Computing eigen value of matrix of covariance */
                   9534:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9535:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9536:                 if ((lc2 <0) || (lc1 <0) ){
                   9537:                   if(first2==1){
                   9538:                     first1=0;
                   9539:                     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);
                   9540:                   }
                   9541:                   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);
                   9542:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   9543:                   /* lc2=fabs(lc2); */
                   9544:                 }
1.220     brouard  9545:                                                                
1.222     brouard  9546:                 /* Eigen vectors */
1.280     brouard  9547:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   9548:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9549:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9550:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   9551:                 }else
                   9552:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  9553:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   9554:                 v21=(lc1-v1)/cv12*v11;
                   9555:                 v12=-v21;
                   9556:                 v22=v11;
                   9557:                 tnalp=v21/v11;
                   9558:                 if(first1==1){
                   9559:                   first1=0;
                   9560:                   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);
                   9561:                 }
                   9562:                 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);
                   9563:                 /*printf(fignu*/
                   9564:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   9565:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   9566:                 if(first==1){
                   9567:                   first=0;
                   9568:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   9569:                   fprintf(ficgp,"\nset parametric;unset label");
                   9570:                   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);
                   9571:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  9572:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  9573:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  9574: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  9575:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   9576:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9577:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9578:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   9579:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9580:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9581:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9582:                   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  9583:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   9584:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  9585:                 }else{
                   9586:                   first=0;
                   9587:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   9588:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9589:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9590:                   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  9591:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   9592:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  9593:                 }/* if first */
                   9594:               } /* age mod 5 */
                   9595:             } /* end loop age */
                   9596:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9597:             first=1;
                   9598:           } /*l12 */
                   9599:         } /* k12 */
                   9600:        } /*l1 */
                   9601:      }/* k1 */
1.332     brouard  9602:    }  /* loop on combination of covariates j1 */
1.326     brouard  9603:    } /* loop on nres */
1.222     brouard  9604:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   9605:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   9606:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9607:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   9608:    free_vector(xp,1,npar);
                   9609:    fclose(ficresprob);
                   9610:    fclose(ficresprobcov);
                   9611:    fclose(ficresprobcor);
                   9612:    fflush(ficgp);
                   9613:    fflush(fichtmcov);
                   9614:  }
1.126     brouard  9615: 
                   9616: 
                   9617: /******************* Printing html file ***********/
1.201     brouard  9618: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9619:                  int lastpass, int stepm, int weightopt, char model[],\
                   9620:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  9621:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   9622:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   9623:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.359     brouard  9624:   int jj1, k1, cpt, nres;
1.319     brouard  9625:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  9626:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   9627:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   9628: </ul>");
1.319     brouard  9629: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   9630: /* </ul>", model); */
1.214     brouard  9631:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   9632:    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",
                   9633:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  9634:    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  9635:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   9636:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  9637:    fprintf(fichtm,"\
                   9638:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  9639:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  9640:    fprintf(fichtm,"\
1.217     brouard  9641:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   9642:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   9643:    fprintf(fichtm,"\
1.288     brouard  9644:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9645:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  9646:    fprintf(fichtm,"\
1.288     brouard  9647:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  9648:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   9649:    fprintf(fichtm,"\
1.211     brouard  9650:  - (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  9651:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9652:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  9653:    if(prevfcast==1){
                   9654:      fprintf(fichtm,"\
                   9655:  - Prevalence projections by age and states:                           \
1.201     brouard  9656:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  9657:    }
1.126     brouard  9658: 
                   9659: 
1.225     brouard  9660:    m=pow(2,cptcoveff);
1.222     brouard  9661:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9662: 
1.317     brouard  9663:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  9664: 
                   9665:    jj1=0;
                   9666: 
                   9667:    fprintf(fichtm," \n<ul>");
1.337     brouard  9668:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9669:      /* k1=nres; */
1.338     brouard  9670:      k1=TKresult[nres];
                   9671:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  9672:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9673:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9674:    /*     continue; */
1.264     brouard  9675:      jj1++;
                   9676:      if (cptcovn > 0) {
                   9677:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  9678:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9679:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9680:        }
1.337     brouard  9681:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9682:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9683:        /* } */
                   9684:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9685:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9686:        /* } */
1.264     brouard  9687:        fprintf(fichtm,"\">");
                   9688:        
                   9689:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9690:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9691:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9692:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9693:        }
1.337     brouard  9694:        /* fprintf(fichtm,"************ Results for covariates"); */
                   9695:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9696:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9697:        /* } */
                   9698:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9699:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9700:        /* } */
1.264     brouard  9701:        if(invalidvarcomb[k1]){
                   9702:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9703:         continue;
                   9704:        }
                   9705:        fprintf(fichtm,"</a></li>");
                   9706:      } /* cptcovn >0 */
                   9707:    }
1.317     brouard  9708:    fprintf(fichtm," \n</ul>");
1.264     brouard  9709: 
1.222     brouard  9710:    jj1=0;
1.237     brouard  9711: 
1.337     brouard  9712:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9713:      /* k1=nres; */
1.338     brouard  9714:      k1=TKresult[nres];
                   9715:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9716:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9717:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9718:    /*     continue; */
1.220     brouard  9719: 
1.222     brouard  9720:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9721:      jj1++;
                   9722:      if (cptcovn > 0) {
1.264     brouard  9723:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  9724:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9725:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9726:        }
1.337     brouard  9727:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9728:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9729:        /* } */
1.264     brouard  9730:        fprintf(fichtm,"\"</a>");
                   9731:  
1.222     brouard  9732:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9733:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9734:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9735:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9736:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   9737:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  9738:        }
1.230     brouard  9739:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  9740:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  9741:        if(invalidvarcomb[k1]){
                   9742:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   9743:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   9744:         continue;
                   9745:        }
                   9746:      }
                   9747:      /* aij, bij */
1.259     brouard  9748:      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  9749: <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  9750:      /* Pij */
1.241     brouard  9751:      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> \
                   9752: <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  9753:      /* Quasi-incidences */
                   9754:      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  9755:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  9756:  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  9757: 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> \
                   9758: <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  9759:      /* Survival functions (period) in state j */
                   9760:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9761:        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. Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. <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);
1.329     brouard  9762:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9763:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  9764:      }
                   9765:      /* State specific survival functions (period) */
                   9766:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  9767:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
1.359     brouard  9768:  And probability to be observed in various states (up to %d) being in state %d at different ages.  Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. \
1.329     brouard  9769:  <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);
                   9770:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9771:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  9772:      }
1.288     brouard  9773:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  9774:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9775:        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 alive 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  9776:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  9777:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  9778:      }
1.296     brouard  9779:      if(prevbcast==1){
1.288     brouard  9780:        /* Backward prevalence in each health state */
1.222     brouard  9781:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  9782:         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);
                   9783:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   9784:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  9785:        }
1.217     brouard  9786:      }
1.222     brouard  9787:      if(prevfcast==1){
1.288     brouard  9788:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  9789:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  9790:         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);
                   9791:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   9792:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   9793:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  9794:        }
                   9795:      }
1.296     brouard  9796:      if(prevbcast==1){
1.268     brouard  9797:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   9798:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  9799:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
1.359     brouard  9800:  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 \
                   9801:  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  9802: 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);
                   9803:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   9804:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  9805:        }
                   9806:      }
1.220     brouard  9807:         
1.222     brouard  9808:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  9809:        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);
                   9810:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   9811:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  9812:      }
                   9813:      /* } /\* end i1 *\/ */
1.337     brouard  9814:    }/* End k1=nres */
1.222     brouard  9815:    fprintf(fichtm,"</ul>");
1.126     brouard  9816: 
1.222     brouard  9817:    fprintf(fichtm,"\
1.126     brouard  9818: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  9819:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  9820:  - 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  9821: But because parameters are usually highly correlated (a higher incidence of disability \
                   9822: and a higher incidence of recovery can give very close observed transition) it might \
                   9823: be very useful to look not only at linear confidence intervals estimated from the \
                   9824: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   9825: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   9826: covariance matrix of the one-step probabilities. \
                   9827: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  9828: 
1.222     brouard  9829:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   9830:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   9831:    fprintf(fichtm,"\
1.126     brouard  9832:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9833:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  9834: 
1.222     brouard  9835:    fprintf(fichtm,"\
1.126     brouard  9836:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9837:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   9838:    fprintf(fichtm,"\
1.126     brouard  9839:  - 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): \
                   9840:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9841:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  9842:    fprintf(fichtm,"\
1.126     brouard  9843:  - (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): \
                   9844:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9845:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  9846:    fprintf(fichtm,"\
1.288     brouard  9847:  - 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  9848:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   9849:    fprintf(fichtm,"\
1.128     brouard  9850:  - 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  9851:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   9852:    fprintf(fichtm,"\
1.288     brouard  9853:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  9854:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  9855: 
                   9856: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   9857: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   9858: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   9859: /*     <br>",fileres,fileres,fileres,fileres); */
                   9860: /*  else  */
1.338     brouard  9861: /*    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  9862:    fflush(fichtm);
1.126     brouard  9863: 
1.225     brouard  9864:    m=pow(2,cptcoveff);
1.222     brouard  9865:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9866: 
1.317     brouard  9867:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   9868: 
                   9869:   jj1=0;
                   9870: 
                   9871:    fprintf(fichtm," \n<ul>");
1.337     brouard  9872:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9873:      /* k1=nres; */
1.338     brouard  9874:      k1=TKresult[nres];
1.337     brouard  9875:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9876:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9877:      /*   continue; */
1.317     brouard  9878:      jj1++;
                   9879:      if (cptcovn > 0) {
                   9880:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  9881:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9882:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9883:        }
                   9884:        fprintf(fichtm,"\">");
                   9885:        
                   9886:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9887:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9888:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9889:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9890:        }
                   9891:        if(invalidvarcomb[k1]){
                   9892:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9893:         continue;
                   9894:        }
                   9895:        fprintf(fichtm,"</a></li>");
                   9896:      } /* cptcovn >0 */
1.337     brouard  9897:    } /* End nres */
1.317     brouard  9898:    fprintf(fichtm," \n</ul>");
                   9899: 
1.222     brouard  9900:    jj1=0;
1.237     brouard  9901: 
1.241     brouard  9902:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9903:      /* k1=nres; */
1.338     brouard  9904:      k1=TKresult[nres];
                   9905:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9906:      /* for(k1=1; k1<=m;k1++){ */
                   9907:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9908:      /*   continue; */
1.222     brouard  9909:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9910:      jj1++;
1.126     brouard  9911:      if (cptcovn > 0) {
1.317     brouard  9912:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  9913:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9914:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9915:        }
                   9916:        fprintf(fichtm,"\"</a>");
                   9917:        
1.126     brouard  9918:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9919:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   9920:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9921:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9922:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  9923:        }
1.237     brouard  9924: 
1.338     brouard  9925:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  9926: 
1.222     brouard  9927:        if(invalidvarcomb[k1]){
                   9928:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   9929:         continue;
                   9930:        }
1.337     brouard  9931:      } /* If cptcovn >0 */
1.126     brouard  9932:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  9933:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  9934: 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);
                   9935:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   9936:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  9937:      }
                   9938:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.360     brouard  9939: health expectancies in each live state (1 to %d) with confidence intervals \
                   9940: on left y-scale as well as proportions of time spent in each live state \
                   9941: (with confidence intervals) on right y-scale 0 to 100%%.\
                   9942:  If popbased=1 the smooth (due to the model)                           \
1.128     brouard  9943: true period expectancies (those weighted with period prevalences are also\
                   9944:  drawn in addition to the population based expectancies computed using\
1.314     brouard  9945:  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);
                   9946:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   9947:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  9948:      /* } /\* end i1 *\/ */
1.241     brouard  9949:   }/* End nres */
1.222     brouard  9950:    fprintf(fichtm,"</ul>");
                   9951:    fflush(fichtm);
1.126     brouard  9952: }
                   9953: 
                   9954: /******************* Gnuplot file **************/
1.296     brouard  9955: 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  9956: 
1.354     brouard  9957:   char dirfileres[256],optfileres[256];
                   9958:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  9959:   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  9960:   int lv=0, vlv=0, kl=0;
1.130     brouard  9961:   int ng=0;
1.201     brouard  9962:   int vpopbased;
1.223     brouard  9963:   int ioffset; /* variable offset for columns */
1.270     brouard  9964:   int iyearc=1; /* variable column for year of projection  */
                   9965:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  9966:   int nres=0; /* Index of resultline */
1.266     brouard  9967:   int istart=1; /* For starting graphs in projections */
1.219     brouard  9968: 
1.126     brouard  9969: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   9970: /*     printf("Problem with file %s",optionfilegnuplot); */
                   9971: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   9972: /*   } */
                   9973: 
                   9974:   /*#ifdef windows */
                   9975:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  9976:   /*#endif */
1.225     brouard  9977:   m=pow(2,cptcoveff);
1.126     brouard  9978: 
1.274     brouard  9979:   /* diagram of the model */
                   9980:   fprintf(ficgp,"\n#Diagram of the model \n");
                   9981:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   9982:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   9983:   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);
                   9984: 
1.343     brouard  9985:   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  9986:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   9987:   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);
                   9988:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   9989:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   9990:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   9991:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   9992: 
1.202     brouard  9993:   /* Contribution to likelihood */
                   9994:   /* Plot the probability implied in the likelihood */
1.223     brouard  9995:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   9996:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   9997:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   9998:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  9999: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  10000:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   10001: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  10002:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   10003:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10004:   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));
                   10005:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10006:   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));
                   10007:   for (i=1; i<= nlstate ; i ++) {
                   10008:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   10009:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   10010:     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);
                   10011:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   10012:       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);
                   10013:     }
                   10014:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10015:   }
                   10016:   /* 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 */               
                   10017:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10018:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10019:   fprintf(ficgp,"\nset out;unset log\n");
                   10020:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  10021: 
1.343     brouard  10022:   /* Plot the probability implied in the likelihood by covariate value */
                   10023:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   10024:   /* if(debugILK==1){ */
                   10025:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  10026:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   10027:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  10028:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  10029:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  10030:     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  10031:     for (i=1; i<= nlstate ; i ++) {
                   10032:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10033:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  10034:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10035:        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);
                   10036:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10037:          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);
                   10038:        }
                   10039:       }else{
                   10040:        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);
                   10041:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10042:          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);
                   10043:        }
1.343     brouard  10044:       }
                   10045:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10046:     }
                   10047:   } /* End of each covariate dummy */
                   10048:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   10049:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   10050:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   10051:      *  varying                   1     2                                 3       4        5
                   10052:      *  ncovv                     1     2                                3 4     5 6      7 8
                   10053:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   10054:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   10055:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   10056:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   10057:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   10058:      */
                   10059:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   10060:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   10061:     /* 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]); */
                   10062:     if(ipos!=iposold){ /* Not a product or first of a product */
                   10063:       /* printf(" %d",ipos); */
                   10064:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   10065:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   10066:       kk++; /* Position of the ncovv column in ILK_ */
                   10067:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   10068:       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)  */
                   10069:        for (i=1; i<= nlstate ; i ++) {
                   10070:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10071:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   10072: 
1.348     brouard  10073:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  10074:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10075:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   10076:            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);
                   10077:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10078:              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);
                   10079:            }
                   10080:          }else{
                   10081:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   10082:            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);
                   10083:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10084:              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);
                   10085:            }
                   10086:          }
                   10087:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10088:        }
                   10089:       }/* End if dummy varying */
                   10090:     }else{ /*Product */
                   10091:       /* printf("*"); */
                   10092:       /* fprintf(ficresilk,"*"); */
                   10093:     }
                   10094:     iposold=ipos;
                   10095:   } /* For each time varying covariate */
                   10096:   /* } /\* debugILK==1 *\/ */
                   10097:   /* 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 */               
                   10098:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10099:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10100:   fprintf(ficgp,"\nset out;unset log\n");
                   10101:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   10102: 
                   10103: 
                   10104:   
1.126     brouard  10105:   strcpy(dirfileres,optionfilefiname);
                   10106:   strcpy(optfileres,"vpl");
1.223     brouard  10107:   /* 1eme*/
1.238     brouard  10108:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  10109:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  10110:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10111:        k1=TKresult[nres];
1.338     brouard  10112:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  10113:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  10114:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10115:        /*   continue; */
1.238     brouard  10116:        /* We are interested in selected combination by the resultline */
1.246     brouard  10117:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  10118:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  10119:        strcpy(gplotlabel,"(");
1.337     brouard  10120:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10121:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10122:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10123: 
                   10124:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   10125:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   10126:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10127:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10128:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10129:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10130:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   10131:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   10132:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   10133:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10134:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10135:        /* } */
                   10136:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10137:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   10138:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10139:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  10140:        }
                   10141:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  10142:        /* printf("\n#\n"); */
1.238     brouard  10143:        fprintf(ficgp,"\n#\n");
                   10144:        if(invalidvarcomb[k1]){
1.260     brouard  10145:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  10146:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10147:          continue;
                   10148:        }
1.235     brouard  10149:       
1.241     brouard  10150:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   10151:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  10152:        /* 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  10153:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  10154:        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);
                   10155:        /* 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); */
                   10156:       /* k1-1 error should be nres-1*/
1.238     brouard  10157:        for (i=1; i<= nlstate ; i ++) {
                   10158:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10159:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   10160:        }
1.288     brouard  10161:        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  10162:        for (i=1; i<= nlstate ; i ++) {
                   10163:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10164:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10165:        } 
1.260     brouard  10166:        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  10167:        for (i=1; i<= nlstate ; i ++) {
                   10168:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10169:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10170:        }  
1.265     brouard  10171:        /* 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)); */
                   10172:        
                   10173:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   10174:         if(cptcoveff ==0){
1.271     brouard  10175:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  10176:        }else{
                   10177:          kl=0;
                   10178:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10179:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10180:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  10181:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10182:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10183:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10184:            vlv= nbcode[Tvaraff[k]][lv];
                   10185:            kl++;
                   10186:            /* 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 *\/ */
                   10187:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10188:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10189:            /* ''  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*/
                   10190:            if(k==cptcoveff){
                   10191:              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], \
                   10192:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   10193:            }else{
                   10194:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   10195:              kl++;
                   10196:            }
                   10197:          } /* end covariate */
                   10198:        } /* end if no covariate */
                   10199: 
1.296     brouard  10200:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  10201:          /* 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  10202:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  10203:          if(cptcoveff ==0){
1.245     brouard  10204:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  10205:          }else{
                   10206:            kl=0;
                   10207:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10208:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10209:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  10210:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10211:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10212:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10213:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   10214:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  10215:              kl++;
1.238     brouard  10216:              /* 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 *\/ */
                   10217:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10218:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10219:              /* ''  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*/
                   10220:              if(k==cptcoveff){
1.245     brouard  10221:                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  10222:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  10223:              }else{
1.332     brouard  10224:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  10225:                kl++;
                   10226:              }
                   10227:            } /* end covariate */
                   10228:          } /* end if no covariate */
1.296     brouard  10229:          if(prevbcast == 1){
1.268     brouard  10230:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   10231:            /* k1-1 error should be nres-1*/
                   10232:            for (i=1; i<= nlstate ; i ++) {
                   10233:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10234:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   10235:            }
1.271     brouard  10236:            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  10237:            for (i=1; i<= nlstate ; i ++) {
                   10238:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10239:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10240:            } 
1.276     brouard  10241:            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  10242:            for (i=1; i<= nlstate ; i ++) {
                   10243:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10244:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10245:            } 
1.274     brouard  10246:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  10247:          } /* end if backprojcast */
1.296     brouard  10248:        } /* end if prevbcast */
1.276     brouard  10249:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   10250:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  10251:       } /* nres */
1.337     brouard  10252:     /* } /\* k1 *\/ */
1.201     brouard  10253:   } /* cpt */
1.235     brouard  10254: 
                   10255:   
1.126     brouard  10256:   /*2 eme*/
1.337     brouard  10257:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  10258:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10259:       k1=TKresult[nres];
1.338     brouard  10260:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10261:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10262:       /*       continue; */
1.238     brouard  10263:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  10264:       strcpy(gplotlabel,"(");
1.337     brouard  10265:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10266:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10267:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10268:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10269:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10270:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10271:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10272:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10273:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10274:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10275:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10276:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10277:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10278:       /* } */
                   10279:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   10280:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10281:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10282:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10283:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  10284:       }
1.264     brouard  10285:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10286:       fprintf(ficgp,"\n#\n");
1.223     brouard  10287:       if(invalidvarcomb[k1]){
                   10288:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10289:        continue;
                   10290:       }
1.219     brouard  10291:                        
1.241     brouard  10292:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  10293:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  10294:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   10295:        if(vpopbased==0){
1.360     brouard  10296:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nunset ytics; unset y2tics; set ytics nomirror; set y2tics 0,10,100;set y2range [0:100];\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  10297:        }else
1.238     brouard  10298:          fprintf(ficgp,"\nreplot ");
1.360     brouard  10299:        for (i=1; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
1.238     brouard  10300:          k=2*i;
1.360     brouard  10301:          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); /* for fixed variables age, popbased, mobilav */
                   10302:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10303:            if (j==i) fprintf(ficgp," %%lf (%%lf)"); /* We want to read e.. i=1,j=1, e.1 i=2,j=2, e.2 i=3,j=3 */
                   10304:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
1.238     brouard  10305:          }   
                   10306:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
1.360     brouard  10307:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1); /* state=i-1=1 to nlstate  */
1.261     brouard  10308:          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  10309:          for (j=1; j<= nlstate+1 ; j ++) {
                   10310:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10311:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10312:          }   
                   10313:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  10314:          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  10315:          for (j=1; j<= nlstate+1 ; j ++) {
                   10316:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10317:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10318:          }   
1.360     brouard  10319:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0,\\\n"); /* ,\\\n added for th percentage graphs */
1.238     brouard  10320:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   10321:        } /* state */
1.360     brouard  10322:        /* again for the percentag spent in state i-1=1 to i-1=nlstate */
                   10323:        for (i=2; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
                   10324:          k=2*i;
                   10325:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d &&  ($4)<=1 && ($4)>=0 ?($4)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased); /* for fixed variables age, popbased, mobilav */
                   10326:          for (j=1; j<= nlstate ; j ++)
                   10327:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10328:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10329:            if (j==i) fprintf(ficgp," %%lf (%%lf)"); /* We want to read e.. i=1,j=1, e.1 i=2,j=2, e.2 i=3,j=3 */
                   10330:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
                   10331:          }   
                   10332:          if (i== 1) fprintf(ficgp,"\" t\"%%TLE\" w l lt %d axis x1y2, \\\n",i); /* Not used */
                   10333:          else fprintf(ficgp,"\" t\"%%LE in state (%d)\" w l lw 2 lt %d axis x1y2, \\\n",i-1,i+1); /* state=i-1=1 to nlstate  */
                   10334:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && ($4-$5*2)<=1 && ($4-$5*2)>=0? ($4-$5*2)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
                   10335:          for (j=1; j<= nlstate ; j ++)
                   10336:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10337:          for (j=1; j<= nlstate+1 ; j ++) {
                   10338:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10339:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10340:          }   
                   10341:          fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,");
                   10342:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && ($4+$5*2)<=1 && ($4+$5*2)>=0 ? ($4+$5*2)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
                   10343:          for (j=1; j<= nlstate ; j ++)
                   10344:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10345:          for (j=1; j<= nlstate+1 ; j ++) {
                   10346:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10347:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10348:          }   
                   10349:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2");
                   10350:          else fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,\\\n");
                   10351:        } /* state for percent */
1.238     brouard  10352:       } /* vpopbased */
1.264     brouard  10353:       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  10354:     } /* end nres */
1.337     brouard  10355:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  10356:        
                   10357:        
                   10358:   /*3eme*/
1.337     brouard  10359:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  10360:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10361:       k1=TKresult[nres];
1.338     brouard  10362:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10363:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10364:       /*       continue; */
1.238     brouard  10365: 
1.332     brouard  10366:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  10367:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  10368:        strcpy(gplotlabel,"(");
1.337     brouard  10369:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10370:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10371:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10372:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10373:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10374:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10375:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10376:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10377:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10378:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10379:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10380:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10381:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10382:        /* } */
                   10383:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10384:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10385:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10386:        }
1.264     brouard  10387:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10388:        fprintf(ficgp,"\n#\n");
                   10389:        if(invalidvarcomb[k1]){
                   10390:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10391:          continue;
                   10392:        }
                   10393:                        
                   10394:        /*       k=2+nlstate*(2*cpt-2); */
                   10395:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  10396:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  10397:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  10398:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  10399: 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  10400:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10401:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10402:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   10403:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10404:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10405:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  10406:                                
1.238     brouard  10407:        */
                   10408:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  10409:          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  10410:          /*    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  10411:                                
1.238     brouard  10412:        } 
1.261     brouard  10413:        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  10414:       }
1.264     brouard  10415:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  10416:     } /* end nres */
1.337     brouard  10417:   /* } /\* end kl 3eme *\/ */
1.126     brouard  10418:   
1.223     brouard  10419:   /* 4eme */
1.201     brouard  10420:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  10421:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  10422:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10423:       k1=TKresult[nres];
1.338     brouard  10424:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10425:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10426:       /*       continue; */
1.238     brouard  10427:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  10428:        strcpy(gplotlabel,"(");
1.337     brouard  10429:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   10430:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10431:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10432:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10433:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10434:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10435:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10436:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10437:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10438:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10439:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10440:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10441:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10442:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10443:        /* } */
                   10444:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10445:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10446:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10447:        }       
1.264     brouard  10448:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10449:        fprintf(ficgp,"\n#\n");
                   10450:        if(invalidvarcomb[k1]){
                   10451:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10452:          continue;
1.223     brouard  10453:        }
1.238     brouard  10454:       
1.241     brouard  10455:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  10456:        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  10457:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10458: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10459:        k=3;
                   10460:        for (i=1; i<= nlstate ; i ++){
                   10461:          if(i==1){
                   10462:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10463:          }else{
                   10464:            fprintf(ficgp,", '' ");
                   10465:          }
                   10466:          l=(nlstate+ndeath)*(i-1)+1;
                   10467:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10468:          for (j=2; j<= nlstate+ndeath ; j ++)
                   10469:            fprintf(ficgp,"+$%d",k+l+j-1);
                   10470:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   10471:        } /* nlstate */
1.264     brouard  10472:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10473:       } /* end cpt state*/ 
                   10474:     } /* end nres */
1.337     brouard  10475:   /* } /\* end covariate k1 *\/   */
1.238     brouard  10476: 
1.220     brouard  10477: /* 5eme */
1.201     brouard  10478:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  10479:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  10480:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10481:       k1=TKresult[nres];
1.338     brouard  10482:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10483:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10484:       /*       continue; */
1.238     brouard  10485:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  10486:        strcpy(gplotlabel,"(");
1.238     brouard  10487:        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  10488:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10489:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10490:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10491:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10492:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10493:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10494:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10495:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10496:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10497:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10498:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10499:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10500:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10501:        /* } */
                   10502:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10503:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10504:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10505:        }       
1.264     brouard  10506:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10507:        fprintf(ficgp,"\n#\n");
                   10508:        if(invalidvarcomb[k1]){
                   10509:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10510:          continue;
                   10511:        }
1.227     brouard  10512:       
1.241     brouard  10513:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  10514:        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  10515:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10516: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10517:        k=3;
                   10518:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10519:          if(j==1)
                   10520:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10521:          else
                   10522:            fprintf(ficgp,", '' ");
                   10523:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10524:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   10525:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   10526:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   10527:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   10528:        } /* nlstate */
                   10529:        fprintf(ficgp,", '' ");
                   10530:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   10531:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10532:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10533:          if(j < nlstate)
                   10534:            fprintf(ficgp,"$%d +",k+l);
                   10535:          else
                   10536:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   10537:        }
1.264     brouard  10538:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10539:       } /* end cpt state*/ 
1.337     brouard  10540:     /* } /\* end covariate *\/   */
1.238     brouard  10541:   } /* end nres */
1.227     brouard  10542:   
1.220     brouard  10543: /* 6eme */
1.202     brouard  10544:   /* CV preval stable (period) for each covariate */
1.337     brouard  10545:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10546:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10547:      k1=TKresult[nres];
1.338     brouard  10548:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10549:      /* if(m != 1 && TKresult[nres]!= k1) */
                   10550:      /*  continue; */
1.255     brouard  10551:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  10552:       strcpy(gplotlabel,"(");      
1.288     brouard  10553:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10554:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10555:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10556:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10557:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10558:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10559:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10560:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10561:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10562:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10563:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10564:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10565:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10566:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10567:       /* } */
                   10568:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10569:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10570:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10571:       }        
1.264     brouard  10572:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10573:       fprintf(ficgp,"\n#\n");
1.223     brouard  10574:       if(invalidvarcomb[k1]){
1.227     brouard  10575:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10576:        continue;
1.223     brouard  10577:       }
1.227     brouard  10578:       
1.241     brouard  10579:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  10580:       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  10581:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10582: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  10583:       k=3; /* Offset */
1.255     brouard  10584:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  10585:        if(i==1)
                   10586:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10587:        else
                   10588:          fprintf(ficgp,", '' ");
1.255     brouard  10589:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  10590:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10591:        for (j=2; j<= nlstate ; j ++)
                   10592:          fprintf(ficgp,"+$%d",k+l+j-1);
                   10593:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  10594:       } /* nlstate */
1.264     brouard  10595:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  10596:     } /* end cpt state*/ 
                   10597:   } /* end covariate */  
1.227     brouard  10598:   
                   10599:   
1.220     brouard  10600: /* 7eme */
1.296     brouard  10601:   if(prevbcast == 1){
1.288     brouard  10602:     /* CV backward prevalence  for each covariate */
1.337     brouard  10603:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10604:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10605:       k1=TKresult[nres];
1.338     brouard  10606:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10607:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10608:       /*       continue; */
1.268     brouard  10609:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  10610:        strcpy(gplotlabel,"(");      
1.288     brouard  10611:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10612:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10613:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10614:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10615:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10616:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10617:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10618:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10619:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10620:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10621:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10622:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10623:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10624:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10625:        /* } */
                   10626:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10627:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10628:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10629:        }       
1.264     brouard  10630:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10631:        fprintf(ficgp,"\n#\n");
                   10632:        if(invalidvarcomb[k1]){
                   10633:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10634:          continue;
                   10635:        }
                   10636:        
1.241     brouard  10637:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  10638:        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  10639:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10640: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  10641:        k=3; /* Offset */
1.268     brouard  10642:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  10643:          if(i==1)
                   10644:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   10645:          else
                   10646:            fprintf(ficgp,", '' ");
                   10647:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  10648:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  10649:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   10650:          /* 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  10651:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  10652:          /* for (j=2; j<= nlstate ; j ++) */
                   10653:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   10654:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  10655:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  10656:        } /* nlstate */
1.264     brouard  10657:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  10658:       } /* end cpt state*/ 
                   10659:     } /* end covariate */  
1.296     brouard  10660:   } /* End if prevbcast */
1.218     brouard  10661:   
1.223     brouard  10662:   /* 8eme */
1.218     brouard  10663:   if(prevfcast==1){
1.288     brouard  10664:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  10665:     
1.337     brouard  10666:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10667:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10668:       k1=TKresult[nres];
1.338     brouard  10669:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10670:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10671:       /*       continue; */
1.211     brouard  10672:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  10673:        strcpy(gplotlabel,"(");      
1.288     brouard  10674:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10675:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10676:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10677:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10678:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10679:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10680:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10681:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10682:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10683:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10684:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10685:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10686:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10687:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10688:        /* } */
                   10689:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10690:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10691:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10692:        }       
1.264     brouard  10693:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10694:        fprintf(ficgp,"\n#\n");
                   10695:        if(invalidvarcomb[k1]){
                   10696:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10697:          continue;
                   10698:        }
                   10699:        
                   10700:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  10701:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  10702:        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  10703:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  10704: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  10705: 
                   10706:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10707:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10708:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10709:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  10710:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10711:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10712:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10713:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  10714:          if(i==istart){
1.227     brouard  10715:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   10716:          }else{
                   10717:            fprintf(ficgp,",\\\n '' ");
                   10718:          }
                   10719:          if(cptcoveff ==0){ /* No covariate */
                   10720:            ioffset=2; /* Age is in 2 */
                   10721:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10722:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10723:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10724:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10725:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  10726:            if(i==nlstate+1){
1.270     brouard  10727:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  10728:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10729:              fprintf(ficgp,",\\\n '' ");
                   10730:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10731:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  10732:                     offyear,                           \
1.268     brouard  10733:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  10734:            }else
1.227     brouard  10735:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   10736:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10737:          }else{ /* more than 2 covariates */
1.270     brouard  10738:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10739:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10740:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10741:            iyearc=ioffset-1;
                   10742:            iagec=ioffset;
1.227     brouard  10743:            fprintf(ficgp," u %d:(",ioffset); 
                   10744:            kl=0;
                   10745:            strcpy(gplotcondition,"(");
1.351     brouard  10746:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  10747:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  10748:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10749:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10750:              lv=Tvresult[nres][k];
                   10751:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  10752:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10753:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10754:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10755:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  10756:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  10757:              kl++;
1.351     brouard  10758:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10759:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  10760:              kl++;
1.351     brouard  10761:              if(k <cptcovs && cptcovs>1)
1.227     brouard  10762:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10763:            }
                   10764:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10765:            /* 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 *\/ */
                   10766:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10767:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10768:            /* ''  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*/
                   10769:            if(i==nlstate+1){
1.270     brouard  10770:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   10771:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  10772:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10773:              fprintf(ficgp," u %d:(",iagec); 
                   10774:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   10775:                      iyearc, iagec, offyear,                           \
                   10776:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  10777: /*  '' 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  10778:            }else{
                   10779:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   10780:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10781:            }
                   10782:          } /* end if covariate */
                   10783:        } /* nlstate */
1.264     brouard  10784:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  10785:       } /* end cpt state*/
                   10786:     } /* end covariate */
                   10787:   } /* End if prevfcast */
1.227     brouard  10788:   
1.296     brouard  10789:   if(prevbcast==1){
1.268     brouard  10790:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   10791:     
1.337     brouard  10792:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  10793:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10794:      k1=TKresult[nres];
1.338     brouard  10795:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10796:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10797:        /*      continue; */
1.268     brouard  10798:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   10799:        strcpy(gplotlabel,"(");      
                   10800:        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  10801:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10802:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10803:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10804:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10805:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10806:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10807:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10808:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10809:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10810:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10811:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10812:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10813:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10814:        /* } */
                   10815:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10816:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10817:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  10818:        }       
                   10819:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   10820:        fprintf(ficgp,"\n#\n");
                   10821:        if(invalidvarcomb[k1]){
                   10822:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10823:          continue;
                   10824:        }
                   10825:        
                   10826:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   10827:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   10828:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   10829:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   10830: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10831: 
                   10832:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10833:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10834:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10835:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   10836:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10837:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10838:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10839:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10840:          if(i==istart){
                   10841:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   10842:          }else{
                   10843:            fprintf(ficgp,",\\\n '' ");
                   10844:          }
1.351     brouard  10845:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   10846:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  10847:            ioffset=2; /* Age is in 2 */
                   10848:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10849:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10850:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10851:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10852:            fprintf(ficgp," u %d:(", ioffset); 
                   10853:            if(i==nlstate+1){
1.270     brouard  10854:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  10855:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10856:              fprintf(ficgp,",\\\n '' ");
                   10857:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10858:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  10859:                     offbyear,                          \
                   10860:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   10861:            }else
                   10862:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   10863:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   10864:          }else{ /* more than 2 covariates */
1.270     brouard  10865:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10866:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10867:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10868:            iyearc=ioffset-1;
                   10869:            iagec=ioffset;
1.268     brouard  10870:            fprintf(ficgp," u %d:(",ioffset); 
                   10871:            kl=0;
                   10872:            strcpy(gplotcondition,"(");
1.337     brouard  10873:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  10874:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  10875:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   10876:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10877:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10878:                lv=Tvresult[nres][k];
                   10879:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   10880:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10881:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10882:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10883:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   10884:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10885:                kl++;
                   10886:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10887:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   10888:                kl++;
1.338     brouard  10889:                if(k <cptcovs && cptcovs>1)
1.337     brouard  10890:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10891:              }
1.268     brouard  10892:            }
                   10893:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10894:            /* 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 *\/ */
                   10895:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10896:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10897:            /* ''  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*/
                   10898:            if(i==nlstate+1){
1.270     brouard  10899:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   10900:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  10901:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10902:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  10903:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  10904:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   10905:                      iyearc,iagec,offbyear,                            \
                   10906:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  10907: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   10908:            }else{
                   10909:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   10910:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   10911:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   10912:            }
                   10913:          } /* end if covariate */
                   10914:        } /* nlstate */
                   10915:        fprintf(ficgp,"\nset out; unset label;\n");
                   10916:       } /* end cpt state*/
                   10917:     } /* end covariate */
1.296     brouard  10918:   } /* End if prevbcast */
1.268     brouard  10919:   
1.227     brouard  10920:   
1.238     brouard  10921:   /* 9eme writing MLE parameters */
                   10922:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  10923:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  10924:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  10925:     for(k=1; k <=(nlstate+ndeath); k++){
                   10926:       if (k != i) {
1.227     brouard  10927:        fprintf(ficgp,"#   current state %d\n",k);
                   10928:        for(j=1; j <=ncovmodel; j++){
                   10929:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   10930:          jk++; 
                   10931:        }
                   10932:        fprintf(ficgp,"\n");
1.126     brouard  10933:       }
                   10934:     }
1.223     brouard  10935:   }
1.187     brouard  10936:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  10937:   
1.145     brouard  10938:   /*goto avoid;*/
1.238     brouard  10939:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   10940:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  10941:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   10942:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   10943:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   10944:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   10945:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10946:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10947:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10948:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10949:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   10950:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10951:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   10952:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   10953:   fprintf(ficgp,"#\n");
1.223     brouard  10954:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  10955:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  10956:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  10957:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  10958:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   10959:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  10960:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  10961:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10962:      /* k1=nres; */
1.338     brouard  10963:       k1=TKresult[nres];
                   10964:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10965:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  10966:       strcpy(gplotlabel,"(");
1.276     brouard  10967:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  10968:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   10969:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   10970:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   10971:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10972:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10973:       }
                   10974:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10975:       /*       continue; */
                   10976:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   10977:       /* strcpy(gplotlabel,"("); */
                   10978:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   10979:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10980:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10981:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10982:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10983:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10984:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10985:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10986:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10987:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10988:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10989:       /* } */
                   10990:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10991:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10992:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10993:       /* }      */
1.264     brouard  10994:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  10995:       fprintf(ficgp,"\n#\n");
1.264     brouard  10996:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  10997:       fprintf(ficgp,"\nset key outside ");
                   10998:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   10999:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  11000:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   11001:       if (ng==1){
                   11002:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   11003:        fprintf(ficgp,"\nunset log y");
                   11004:       }else if (ng==2){
                   11005:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   11006:        fprintf(ficgp,"\nset log y");
                   11007:       }else if (ng==3){
                   11008:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   11009:        fprintf(ficgp,"\nset log y");
                   11010:       }else
                   11011:        fprintf(ficgp,"\nunset title ");
                   11012:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   11013:       i=1;
                   11014:       for(k2=1; k2<=nlstate; k2++) {
                   11015:        k3=i;
                   11016:        for(k=1; k<=(nlstate+ndeath); k++) {
                   11017:          if (k != k2){
                   11018:            switch( ng) {
                   11019:            case 1:
                   11020:              if(nagesqr==0)
                   11021:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   11022:              else /* nagesqr =1 */
                   11023:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11024:              break;
                   11025:            case 2: /* ng=2 */
                   11026:              if(nagesqr==0)
                   11027:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   11028:              else /* nagesqr =1 */
                   11029:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11030:              break;
                   11031:            case 3:
                   11032:              if(nagesqr==0)
                   11033:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   11034:              else /* nagesqr =1 */
                   11035:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   11036:              break;
                   11037:            }
                   11038:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  11039:            ijp=1; /* product no age */
                   11040:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   11041:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  11042:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  11043:              switch(Typevar[j]){
                   11044:              case 1:
                   11045:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11046:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   11047:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11048:                      if(DummyV[j]==0){/* Bug valgrind */
                   11049:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   11050:                      }else{ /* quantitative */
                   11051:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11052:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11053:                      }
                   11054:                      ij++;
1.268     brouard  11055:                    }
1.237     brouard  11056:                  }
1.329     brouard  11057:                }
                   11058:                break;
                   11059:              case 2:
                   11060:                if(cptcovprod >0){
                   11061:                  if(j==Tprod[ijp]) { /* */ 
                   11062:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11063:                    if(ijp <=cptcovprod) { /* Product */
                   11064:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11065:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11066:                          /* 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)]); */
                   11067:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11068:                        }else{ /* Vn is dummy and Vm is quanti */
                   11069:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11070:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11071:                        }
                   11072:                      }else{ /* Vn*Vm Vn is quanti */
                   11073:                        if(DummyV[Tvard[ijp][2]]==0){
                   11074:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11075:                        }else{ /* Both quanti */
                   11076:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11077:                        }
1.268     brouard  11078:                      }
1.329     brouard  11079:                      ijp++;
1.237     brouard  11080:                    }
1.329     brouard  11081:                  } /* end Tprod */
                   11082:                }
                   11083:                break;
1.349     brouard  11084:              case 3:
                   11085:                if(cptcovdageprod >0){
                   11086:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   11087:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  11088:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   11089:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11090:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11091:                          /* 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)]); */
                   11092:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11093:                        }else{ /* Vn is dummy and Vm is quanti */
                   11094:                          /* 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  11095:                          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  11096:                        }
1.350     brouard  11097:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  11098:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  11099:                          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  11100:                        }else{ /* Both quanti */
1.350     brouard  11101:                          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  11102:                        }
                   11103:                      }
                   11104:                      ijp++;
                   11105:                    }
                   11106:                    /* } */ /* end Tprod */
                   11107:                }
                   11108:                break;
1.329     brouard  11109:              case 0:
                   11110:                /* simple covariate */
1.264     brouard  11111:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  11112:                if(Dummy[j]==0){
                   11113:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   11114:                }else{ /* quantitative */
                   11115:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  11116:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  11117:                }
1.329     brouard  11118:               /* end simple */
                   11119:                break;
                   11120:              default:
                   11121:                break;
                   11122:              } /* end switch */
1.237     brouard  11123:            } /* end j */
1.329     brouard  11124:          }else{ /* k=k2 */
                   11125:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   11126:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   11127:            }else
                   11128:              i=i-ncovmodel;
1.223     brouard  11129:          }
1.227     brouard  11130:          
1.223     brouard  11131:          if(ng != 1){
                   11132:            fprintf(ficgp,")/(1");
1.227     brouard  11133:            
1.264     brouard  11134:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  11135:              if(nagesqr==0)
1.264     brouard  11136:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  11137:              else /* nagesqr =1 */
1.264     brouard  11138:                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  11139:               
1.223     brouard  11140:              ij=1;
1.329     brouard  11141:              ijp=1;
                   11142:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   11143:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   11144:                switch(Typevar[j]){
                   11145:                case 1:
                   11146:                  if(cptcovage >0){ 
                   11147:                    if(j==Tage[ij]) { /* Bug valgrind */
                   11148:                      if(ij <=cptcovage) { /* Bug valgrind */
                   11149:                        if(DummyV[j]==0){/* Bug valgrind */
                   11150:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   11151:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   11152:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   11153:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   11154:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11155:                        }else{ /* quantitative */
                   11156:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11157:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11158:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11159:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11160:                        }
                   11161:                        ij++;
                   11162:                      }
                   11163:                    }
                   11164:                  }
                   11165:                  break;
                   11166:                case 2:
                   11167:                  if(cptcovprod >0){
                   11168:                    if(j==Tprod[ijp]) { /* */ 
                   11169:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11170:                      if(ijp <=cptcovprod) { /* Product */
                   11171:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11172:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11173:                            /* 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)]); */
                   11174:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11175:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11176:                          }else{ /* Vn is dummy and Vm is quanti */
                   11177:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11178:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11179:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11180:                          }
                   11181:                        }else{ /* Vn*Vm Vn is quanti */
                   11182:                          if(DummyV[Tvard[ijp][2]]==0){
                   11183:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11184:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11185:                          }else{ /* Both quanti */
                   11186:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11187:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11188:                          } 
                   11189:                        }
                   11190:                        ijp++;
                   11191:                      }
                   11192:                    } /* end Tprod */
                   11193:                  } /* end if */
                   11194:                  break;
1.349     brouard  11195:                case 3:
                   11196:                  if(cptcovdageprod >0){
                   11197:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   11198:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11199:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  11200:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11201:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11202:                            /* 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  11203:                            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  11204:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11205:                          }else{ /* Vn is dummy and Vm is quanti */
                   11206:                            /* 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  11207:                            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  11208:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11209:                          }
                   11210:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  11211:                          if(DummyV[Tvardk[ijp][2]]==0){
                   11212:                            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  11213:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11214:                          }else{ /* Both quanti */
1.350     brouard  11215:                            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  11216:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11217:                          } 
                   11218:                        }
                   11219:                        ijp++;
                   11220:                      }
                   11221:                    /* } /\* end Tprod *\/ */
                   11222:                  } /* end if */
                   11223:                  break;
1.329     brouard  11224:                case 0: 
                   11225:                  /* simple covariate */
                   11226:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   11227:                  if(Dummy[j]==0){
                   11228:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11229:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   11230:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11231:                  }else{ /* quantitative */
                   11232:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   11233:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   11234:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11235:                  }
                   11236:                  /* end simple */
                   11237:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   11238:                  break;
                   11239:                default:
                   11240:                  break;
                   11241:                } /* end switch */
1.223     brouard  11242:              }
                   11243:              fprintf(ficgp,")");
                   11244:            }
                   11245:            fprintf(ficgp,")");
                   11246:            if(ng ==2)
1.276     brouard  11247:              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  11248:            else /* ng= 3 */
1.276     brouard  11249:              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  11250:           }else{ /* end ng <> 1 */
1.223     brouard  11251:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  11252:              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  11253:          }
                   11254:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   11255:            fprintf(ficgp,",");
                   11256:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   11257:            fprintf(ficgp,",");
                   11258:          i=i+ncovmodel;
                   11259:        } /* end k */
                   11260:       } /* end k2 */
1.276     brouard  11261:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   11262:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  11263:     } /* end resultline */
1.223     brouard  11264:   } /* end ng */
                   11265:   /* avoid: */
                   11266:   fflush(ficgp); 
1.126     brouard  11267: }  /* end gnuplot */
                   11268: 
                   11269: 
                   11270: /*************** Moving average **************/
1.219     brouard  11271: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  11272:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  11273:    
1.222     brouard  11274:    int i, cpt, cptcod;
                   11275:    int modcovmax =1;
                   11276:    int mobilavrange, mob;
                   11277:    int iage=0;
1.288     brouard  11278:    int firstA1=0, firstA2=0;
1.222     brouard  11279: 
1.266     brouard  11280:    double sum=0., sumr=0.;
1.222     brouard  11281:    double age;
1.266     brouard  11282:    double *sumnewp, *sumnewm, *sumnewmr;
                   11283:    double *agemingood, *agemaxgood; 
                   11284:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  11285:   
                   11286:   
1.278     brouard  11287:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   11288:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  11289: 
                   11290:    sumnewp = vector(1,ncovcombmax);
                   11291:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  11292:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  11293:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  11294:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  11295:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  11296:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  11297: 
                   11298:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  11299:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  11300:      sumnewp[cptcod]=0.;
1.266     brouard  11301:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   11302:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  11303:    }
                   11304:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   11305:   
1.266     brouard  11306:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   11307:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  11308:      else mobilavrange=mobilav;
                   11309:      for (age=bage; age<=fage; age++)
                   11310:        for (i=1; i<=nlstate;i++)
                   11311:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   11312:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11313:      /* We keep the original values on the extreme ages bage, fage and for 
                   11314:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   11315:        we use a 5 terms etc. until the borders are no more concerned. 
                   11316:      */ 
                   11317:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   11318:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  11319:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   11320:           sumnewm[cptcod]=0.;
                   11321:           for (i=1; i<=nlstate;i++){
1.222     brouard  11322:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   11323:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   11324:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   11325:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   11326:             }
                   11327:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  11328:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11329:           } /* end i */
                   11330:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   11331:         } /* end cptcod */
1.222     brouard  11332:        }/* end age */
                   11333:      }/* end mob */
1.266     brouard  11334:    }else{
                   11335:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  11336:      return -1;
1.266     brouard  11337:    }
                   11338: 
                   11339:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  11340:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   11341:      if(invalidvarcomb[cptcod]){
                   11342:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   11343:        continue;
                   11344:      }
1.219     brouard  11345: 
1.266     brouard  11346:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   11347:        sumnewm[cptcod]=0.;
                   11348:        sumnewmr[cptcod]=0.;
                   11349:        for (i=1; i<=nlstate;i++){
                   11350:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11351:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11352:        }
                   11353:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11354:         agemingoodr[cptcod]=age;
                   11355:        }
                   11356:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11357:           agemingood[cptcod]=age;
                   11358:        }
                   11359:      } /* age */
                   11360:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  11361:        sumnewm[cptcod]=0.;
1.266     brouard  11362:        sumnewmr[cptcod]=0.;
1.222     brouard  11363:        for (i=1; i<=nlstate;i++){
                   11364:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11365:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11366:        }
                   11367:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11368:         agemaxgoodr[cptcod]=age;
1.222     brouard  11369:        }
                   11370:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  11371:         agemaxgood[cptcod]=age;
                   11372:        }
                   11373:      } /* age */
                   11374:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   11375:      /* but they will change */
1.288     brouard  11376:      firstA1=0;firstA2=0;
1.266     brouard  11377:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   11378:        sumnewm[cptcod]=0.;
                   11379:        sumnewmr[cptcod]=0.;
                   11380:        for (i=1; i<=nlstate;i++){
                   11381:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11382:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11383:        }
                   11384:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11385:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11386:           agemaxgoodr[cptcod]=age;  /* age min */
                   11387:           for (i=1; i<=nlstate;i++)
                   11388:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11389:         }else{ /* bad we change the value with the values of good ages */
                   11390:           for (i=1; i<=nlstate;i++){
                   11391:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   11392:           } /* i */
                   11393:         } /* end bad */
                   11394:        }else{
                   11395:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11396:           agemaxgood[cptcod]=age;
                   11397:         }else{ /* bad we change the value with the values of good ages */
                   11398:           for (i=1; i<=nlstate;i++){
                   11399:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   11400:           } /* i */
                   11401:         } /* end bad */
                   11402:        }/* end else */
                   11403:        sum=0.;sumr=0.;
                   11404:        for (i=1; i<=nlstate;i++){
                   11405:         sum+=mobaverage[(int)age][i][cptcod];
                   11406:         sumr+=probs[(int)age][i][cptcod];
                   11407:        }
                   11408:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  11409:         if(!firstA1){
                   11410:           firstA1=1;
                   11411:           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);
                   11412:         }
                   11413:         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  11414:        } /* end bad */
                   11415:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11416:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  11417:         if(!firstA2){
                   11418:           firstA2=1;
                   11419:           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);
                   11420:         }
                   11421:         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  11422:        } /* end bad */
                   11423:      }/* age */
1.266     brouard  11424: 
                   11425:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  11426:        sumnewm[cptcod]=0.;
1.266     brouard  11427:        sumnewmr[cptcod]=0.;
1.222     brouard  11428:        for (i=1; i<=nlstate;i++){
                   11429:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11430:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11431:        } 
                   11432:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11433:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   11434:           agemingoodr[cptcod]=age;
                   11435:           for (i=1; i<=nlstate;i++)
                   11436:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11437:         }else{ /* bad we change the value with the values of good ages */
                   11438:           for (i=1; i<=nlstate;i++){
                   11439:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   11440:           } /* i */
                   11441:         } /* end bad */
                   11442:        }else{
                   11443:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11444:           agemingood[cptcod]=age;
                   11445:         }else{ /* bad */
                   11446:           for (i=1; i<=nlstate;i++){
                   11447:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   11448:           } /* i */
                   11449:         } /* end bad */
                   11450:        }/* end else */
                   11451:        sum=0.;sumr=0.;
                   11452:        for (i=1; i<=nlstate;i++){
                   11453:         sum+=mobaverage[(int)age][i][cptcod];
                   11454:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  11455:        }
1.266     brouard  11456:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  11457:         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  11458:        } /* end bad */
                   11459:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11460:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  11461:         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  11462:        } /* end bad */
                   11463:      }/* age */
1.266     brouard  11464: 
1.222     brouard  11465:                
                   11466:      for (age=bage; age<=fage; age++){
1.235     brouard  11467:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  11468:        sumnewp[cptcod]=0.;
                   11469:        sumnewm[cptcod]=0.;
                   11470:        for (i=1; i<=nlstate;i++){
                   11471:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   11472:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11473:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   11474:        }
                   11475:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   11476:      }
                   11477:      /* printf("\n"); */
                   11478:      /* } */
1.266     brouard  11479: 
1.222     brouard  11480:      /* brutal averaging */
1.266     brouard  11481:      /* for (i=1; i<=nlstate;i++){ */
                   11482:      /*   for (age=1; age<=bage; age++){ */
                   11483:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   11484:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11485:      /*   }     */
                   11486:      /*   for (age=fage; age<=AGESUP; age++){ */
                   11487:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   11488:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11489:      /*   } */
                   11490:      /* } /\* end i status *\/ */
                   11491:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   11492:      /*   for (age=1; age<=AGESUP; age++){ */
                   11493:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   11494:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   11495:      /*   } */
                   11496:      /* } */
1.222     brouard  11497:    }/* end cptcod */
1.266     brouard  11498:    free_vector(agemaxgoodr,1, ncovcombmax);
                   11499:    free_vector(agemaxgood,1, ncovcombmax);
                   11500:    free_vector(agemingood,1, ncovcombmax);
                   11501:    free_vector(agemingoodr,1, ncovcombmax);
                   11502:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  11503:    free_vector(sumnewm,1, ncovcombmax);
                   11504:    free_vector(sumnewp,1, ncovcombmax);
                   11505:    return 0;
                   11506:  }/* End movingaverage */
1.218     brouard  11507:  
1.126     brouard  11508: 
1.296     brouard  11509:  
1.126     brouard  11510: /************** Forecasting ******************/
1.296     brouard  11511: /* 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)*/
                   11512: 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){
                   11513:   /* dateintemean, mean date of interviews
                   11514:      dateprojd, year, month, day of starting projection 
                   11515:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  11516:      agemin, agemax range of age
                   11517:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   11518:   */
1.296     brouard  11519:   /* double anprojd, mprojd, jprojd; */
                   11520:   /* double anprojf, mprojf, jprojf; */
1.359     brouard  11521:   int yearp, stepsize, hstepm, nhstepm, j, k, i, h,  nres=0;
1.126     brouard  11522:   double agec; /* generic age */
1.359     brouard  11523:   double agelim, ppij;
                   11524:   /*double *popcount;*/
1.126     brouard  11525:   double ***p3mat;
1.218     brouard  11526:   /* double ***mobaverage; */
1.126     brouard  11527:   char fileresf[FILENAMELENGTH];
                   11528: 
                   11529:   agelim=AGESUP;
1.211     brouard  11530:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11531:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11532:      We still use firstpass and lastpass as another selection.
                   11533:   */
1.214     brouard  11534:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11535:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  11536:  
1.201     brouard  11537:   strcpy(fileresf,"F_"); 
                   11538:   strcat(fileresf,fileresu);
1.126     brouard  11539:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   11540:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   11541:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   11542:   }
1.235     brouard  11543:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   11544:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  11545: 
1.225     brouard  11546:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  11547: 
                   11548: 
                   11549:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11550:   if (stepm<=12) stepsize=1;
                   11551:   if(estepm < stepm){
                   11552:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11553:   }
1.270     brouard  11554:   else{
                   11555:     hstepm=estepm;   
                   11556:   }
                   11557:   if(estepm > stepm){ /* Yes every two year */
                   11558:     stepsize=2;
                   11559:   }
1.296     brouard  11560:   hstepm=hstepm/stepm;
1.126     brouard  11561: 
1.296     brouard  11562:   
                   11563:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11564:   /*                              fractional in yp1 *\/ */
                   11565:   /* aintmean=yp; */
                   11566:   /* yp2=modf((yp1*12),&yp); */
                   11567:   /* mintmean=yp; */
                   11568:   /* yp1=modf((yp2*30.5),&yp); */
                   11569:   /* jintmean=yp; */
                   11570:   /* if(jintmean==0) jintmean=1; */
                   11571:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  11572: 
1.296     brouard  11573: 
                   11574:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   11575:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   11576:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  11577:   /* i1=pow(2,cptcoveff); */
                   11578:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  11579:   
1.296     brouard  11580:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  11581:   
                   11582:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  11583:   
1.126     brouard  11584: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  11585:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11586:     k=TKresult[nres];
                   11587:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11588:     /*  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) *\/ */
                   11589:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11590:     /*   continue; */
                   11591:     /* if(invalidvarcomb[k]){ */
                   11592:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11593:     /*   continue; */
                   11594:     /* } */
1.227     brouard  11595:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  11596:     for(j=1;j<=cptcovs;j++){
                   11597:       /* for(j=1;j<=cptcoveff;j++) { */
                   11598:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   11599:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11600:     /* } */
                   11601:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11602:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11603:     /* } */
                   11604:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  11605:     }
1.351     brouard  11606:  
1.227     brouard  11607:     fprintf(ficresf," yearproj age");
                   11608:     for(j=1; j<=nlstate+ndeath;j++){ 
                   11609:       for(i=1; i<=nlstate;i++)               
                   11610:        fprintf(ficresf," p%d%d",i,j);
                   11611:       fprintf(ficresf," wp.%d",j);
                   11612:     }
1.296     brouard  11613:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  11614:       fprintf(ficresf,"\n");
1.296     brouard  11615:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  11616:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   11617:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  11618:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   11619:        nhstepm = nhstepm/hstepm; 
                   11620:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11621:        oldm=oldms;savm=savms;
1.268     brouard  11622:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  11623:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  11624:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  11625:        for (h=0; h<=nhstepm; h++){
                   11626:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  11627:            break;
                   11628:          }
                   11629:        }
                   11630:        fprintf(ficresf,"\n");
1.351     brouard  11631:        /* for(j=1;j<=cptcoveff;j++)  */
                   11632:        for(j=1;j<=cptcovs;j++) 
                   11633:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  11634:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  11635:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  11636:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  11637:        
                   11638:        for(j=1; j<=nlstate+ndeath;j++) {
                   11639:          ppij=0.;
                   11640:          for(i=1; i<=nlstate;i++) {
1.278     brouard  11641:            if (mobilav>=1)
                   11642:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   11643:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   11644:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   11645:            }
1.268     brouard  11646:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   11647:          } /* end i */
                   11648:          fprintf(ficresf," %.3f", ppij);
                   11649:        }/* end j */
1.227     brouard  11650:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11651:       } /* end agec */
1.266     brouard  11652:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   11653:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  11654:     } /* end yearp */
                   11655:   } /* end  k */
1.219     brouard  11656:        
1.126     brouard  11657:   fclose(ficresf);
1.215     brouard  11658:   printf("End of Computing forecasting \n");
                   11659:   fprintf(ficlog,"End of Computing forecasting\n");
                   11660: 
1.126     brouard  11661: }
                   11662: 
1.269     brouard  11663: /************** Back Forecasting ******************/
1.296     brouard  11664:  /* 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){ */
                   11665:  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){
                   11666:   /* back1, year, month, day of starting backprojection
1.267     brouard  11667:      agemin, agemax range of age
                   11668:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  11669:      anback2 year of end of backprojection (same day and month as back1).
                   11670:      prevacurrent and prev are prevalences.
1.267     brouard  11671:   */
1.359     brouard  11672:   int yearp, stepsize, hstepm, nhstepm, j, k,  i, h, nres=0;
1.267     brouard  11673:   double agec; /* generic age */
1.359     brouard  11674:   double agelim, ppij, ppi; /* ,jintmean,mintmean,aintmean;*/
                   11675:   /*double *popcount;*/
1.267     brouard  11676:   double ***p3mat;
                   11677:   /* double ***mobaverage; */
                   11678:   char fileresfb[FILENAMELENGTH];
                   11679:  
1.268     brouard  11680:   agelim=AGEINF;
1.267     brouard  11681:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11682:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11683:      We still use firstpass and lastpass as another selection.
                   11684:   */
                   11685:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11686:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   11687: 
                   11688:   /*Do we need to compute prevalence again?*/
                   11689: 
                   11690:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11691:   
                   11692:   strcpy(fileresfb,"FB_");
                   11693:   strcat(fileresfb,fileresu);
                   11694:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   11695:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   11696:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   11697:   }
                   11698:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11699:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11700:   
                   11701:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   11702:   
                   11703:    
                   11704:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11705:   if (stepm<=12) stepsize=1;
                   11706:   if(estepm < stepm){
                   11707:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11708:   }
1.270     brouard  11709:   else{
                   11710:     hstepm=estepm;   
                   11711:   }
                   11712:   if(estepm >= stepm){ /* Yes every two year */
                   11713:     stepsize=2;
                   11714:   }
1.267     brouard  11715:   
                   11716:   hstepm=hstepm/stepm;
1.296     brouard  11717:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11718:   /*                              fractional in yp1 *\/ */
                   11719:   /* aintmean=yp; */
                   11720:   /* yp2=modf((yp1*12),&yp); */
                   11721:   /* mintmean=yp; */
                   11722:   /* yp1=modf((yp2*30.5),&yp); */
                   11723:   /* jintmean=yp; */
                   11724:   /* if(jintmean==0) jintmean=1; */
                   11725:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  11726:   
1.351     brouard  11727:   /* i1=pow(2,cptcoveff); */
                   11728:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  11729:   
1.296     brouard  11730:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   11731:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  11732:   
                   11733:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   11734:   
1.351     brouard  11735:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11736:     k=TKresult[nres];
                   11737:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11738:   /* for(k=1; k<=i1;k++){ */
                   11739:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   11740:   /*     continue; */
                   11741:   /*   if(invalidvarcomb[k]){ */
                   11742:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11743:   /*     continue; */
                   11744:   /*   } */
1.268     brouard  11745:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  11746:     for(j=1;j<=cptcovs;j++){
                   11747:     /* for(j=1;j<=cptcoveff;j++) { */
                   11748:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11749:     /* } */
                   11750:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  11751:     }
1.351     brouard  11752:    /*  fprintf(ficrespij,"******\n"); */
                   11753:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11754:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11755:    /*  } */
1.267     brouard  11756:     fprintf(ficresfb," yearbproj age");
                   11757:     for(j=1; j<=nlstate+ndeath;j++){
                   11758:       for(i=1; i<=nlstate;i++)
1.268     brouard  11759:        fprintf(ficresfb," b%d%d",i,j);
                   11760:       fprintf(ficresfb," b.%d",j);
1.267     brouard  11761:     }
1.296     brouard  11762:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  11763:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   11764:       fprintf(ficresfb,"\n");
1.296     brouard  11765:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  11766:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  11767:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   11768:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  11769:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  11770:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  11771:        nhstepm = nhstepm/hstepm;
                   11772:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11773:        oldm=oldms;savm=savms;
1.268     brouard  11774:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  11775:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  11776:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  11777:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   11778:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   11779:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  11780:        for (h=0; h<=nhstepm; h++){
1.268     brouard  11781:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   11782:            break;
                   11783:          }
                   11784:        }
                   11785:        fprintf(ficresfb,"\n");
1.351     brouard  11786:        /* for(j=1;j<=cptcoveff;j++) */
                   11787:        for(j=1;j<=cptcovs;j++)
                   11788:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11789:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  11790:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  11791:        for(i=1; i<=nlstate+ndeath;i++) {
                   11792:          ppij=0.;ppi=0.;
                   11793:          for(j=1; j<=nlstate;j++) {
                   11794:            /* if (mobilav==1) */
1.269     brouard  11795:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   11796:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   11797:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   11798:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  11799:              /* else { */
                   11800:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   11801:              /* } */
1.268     brouard  11802:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   11803:          } /* end j */
                   11804:          if(ppi <0.99){
                   11805:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11806:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11807:          }
                   11808:          fprintf(ficresfb," %.3f", ppij);
                   11809:        }/* end j */
1.267     brouard  11810:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11811:       } /* end agec */
                   11812:     } /* end yearp */
                   11813:   } /* end k */
1.217     brouard  11814:   
1.267     brouard  11815:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  11816:   
1.267     brouard  11817:   fclose(ficresfb);
                   11818:   printf("End of Computing Back forecasting \n");
                   11819:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  11820:        
1.267     brouard  11821: }
1.217     brouard  11822: 
1.269     brouard  11823: /* Variance of prevalence limit: varprlim */
                   11824:  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  11825:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  11826:  
                   11827:    char fileresvpl[FILENAMELENGTH];  
                   11828:    FILE *ficresvpl;
                   11829:    double **oldm, **savm;
                   11830:    double **varpl; /* Variances of prevalence limits by age */   
                   11831:    int i1, k, nres, j ;
                   11832:    
                   11833:     strcpy(fileresvpl,"VPL_");
                   11834:     strcat(fileresvpl,fileresu);
                   11835:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  11836:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  11837:       exit(0);
                   11838:     }
1.288     brouard  11839:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11840:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  11841:     
                   11842:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11843:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11844:     
                   11845:     i1=pow(2,cptcoveff);
                   11846:     if (cptcovn < 1){i1=1;}
                   11847: 
1.337     brouard  11848:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11849:        k=TKresult[nres];
1.338     brouard  11850:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11851:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  11852:       if(i1 != 1 && TKresult[nres]!= k)
                   11853:        continue;
                   11854:       fprintf(ficresvpl,"\n#****** ");
                   11855:       printf("\n#****** ");
                   11856:       fprintf(ficlog,"\n#****** ");
1.337     brouard  11857:       for(j=1;j<=cptcovs;j++) {
                   11858:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11859:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11860:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11861:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11862:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  11863:       }
1.337     brouard  11864:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11865:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11866:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11867:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11868:       /* }      */
1.269     brouard  11869:       fprintf(ficresvpl,"******\n");
                   11870:       printf("******\n");
                   11871:       fprintf(ficlog,"******\n");
                   11872:       
                   11873:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11874:       oldm=oldms;savm=savms;
                   11875:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   11876:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   11877:       /*}*/
                   11878:     }
                   11879:     
                   11880:     fclose(ficresvpl);
1.288     brouard  11881:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   11882:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  11883: 
                   11884:  }
                   11885: /* Variance of back prevalence: varbprlim */
                   11886:  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){
                   11887:       /*------- Variance of back (stable) prevalence------*/
                   11888: 
                   11889:    char fileresvbl[FILENAMELENGTH];  
                   11890:    FILE  *ficresvbl;
                   11891: 
                   11892:    double **oldm, **savm;
                   11893:    double **varbpl; /* Variances of back prevalence limits by age */   
                   11894:    int i1, k, nres, j ;
                   11895: 
                   11896:    strcpy(fileresvbl,"VBL_");
                   11897:    strcat(fileresvbl,fileresu);
                   11898:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   11899:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   11900:      exit(0);
                   11901:    }
                   11902:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   11903:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   11904:    
                   11905:    
                   11906:    i1=pow(2,cptcoveff);
                   11907:    if (cptcovn < 1){i1=1;}
                   11908:    
1.337     brouard  11909:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11910:      k=TKresult[nres];
1.338     brouard  11911:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11912:     /* for(k=1; k<=i1;k++){ */
                   11913:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   11914:     /*          continue; */
1.269     brouard  11915:        fprintf(ficresvbl,"\n#****** ");
                   11916:        printf("\n#****** ");
                   11917:        fprintf(ficlog,"\n#****** ");
1.337     brouard  11918:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  11919:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11920:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11921:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  11922:        /* for(j=1;j<=cptcoveff;j++) { */
                   11923:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11924:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11925:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11926:        /* } */
                   11927:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11928:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11929:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11930:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  11931:        }
                   11932:        fprintf(ficresvbl,"******\n");
                   11933:        printf("******\n");
                   11934:        fprintf(ficlog,"******\n");
                   11935:        
                   11936:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11937:        oldm=oldms;savm=savms;
                   11938:        
                   11939:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   11940:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   11941:        /*}*/
                   11942:      }
                   11943:    
                   11944:    fclose(ficresvbl);
                   11945:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   11946:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   11947: 
                   11948:  } /* End of varbprlim */
                   11949: 
1.126     brouard  11950: /************** Forecasting *****not tested NB*************/
1.227     brouard  11951: /* 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  11952:   
1.227     brouard  11953: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   11954: /*   int *popage; */
                   11955: /*   double calagedatem, agelim, kk1, kk2; */
                   11956: /*   double *popeffectif,*popcount; */
                   11957: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   11958: /*   /\* double ***mobaverage; *\/ */
                   11959: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  11960: 
1.227     brouard  11961: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11962: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11963: /*   agelim=AGESUP; */
                   11964: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  11965:   
1.227     brouard  11966: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  11967:   
                   11968:   
1.227     brouard  11969: /*   strcpy(filerespop,"POP_");  */
                   11970: /*   strcat(filerespop,fileresu); */
                   11971: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   11972: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   11973: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   11974: /*   } */
                   11975: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   11976: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  11977: 
1.227     brouard  11978: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  11979: 
1.227     brouard  11980: /*   /\* if (mobilav!=0) { *\/ */
                   11981: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   11982: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   11983: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   11984: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   11985: /*   /\*   } *\/ */
                   11986: /*   /\* } *\/ */
1.126     brouard  11987: 
1.227     brouard  11988: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   11989: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  11990:   
1.227     brouard  11991: /*   agelim=AGESUP; */
1.126     brouard  11992:   
1.227     brouard  11993: /*   hstepm=1; */
                   11994: /*   hstepm=hstepm/stepm;  */
1.218     brouard  11995:        
1.227     brouard  11996: /*   if (popforecast==1) { */
                   11997: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   11998: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   11999: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   12000: /*     }  */
                   12001: /*     popage=ivector(0,AGESUP); */
                   12002: /*     popeffectif=vector(0,AGESUP); */
                   12003: /*     popcount=vector(0,AGESUP); */
1.126     brouard  12004:     
1.227     brouard  12005: /*     i=1;    */
                   12006: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  12007:     
1.227     brouard  12008: /*     imx=i; */
                   12009: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   12010: /*   } */
1.218     brouard  12011:   
1.227     brouard  12012: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   12013: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   12014: /*       k=k+1; */
                   12015: /*       fprintf(ficrespop,"\n#******"); */
                   12016: /*       for(j=1;j<=cptcoveff;j++) { */
                   12017: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   12018: /*       } */
                   12019: /*       fprintf(ficrespop,"******\n"); */
                   12020: /*       fprintf(ficrespop,"# Age"); */
                   12021: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   12022: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  12023:       
1.227     brouard  12024: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   12025: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  12026:        
1.227     brouard  12027: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12028: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12029: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12030:          
1.227     brouard  12031: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12032: /*       oldm=oldms;savm=savms; */
                   12033: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  12034:          
1.227     brouard  12035: /*       for (h=0; h<=nhstepm; h++){ */
                   12036: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12037: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12038: /*         }  */
                   12039: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12040: /*           kk1=0.;kk2=0; */
                   12041: /*           for(i=1; i<=nlstate;i++) {               */
                   12042: /*             if (mobilav==1)  */
                   12043: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   12044: /*             else { */
                   12045: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   12046: /*             } */
                   12047: /*           } */
                   12048: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   12049: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   12050: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   12051: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   12052: /*           } */
                   12053: /*         } */
                   12054: /*         for(i=1; i<=nlstate;i++){ */
                   12055: /*           kk1=0.; */
                   12056: /*           for(j=1; j<=nlstate;j++){ */
                   12057: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   12058: /*           } */
                   12059: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   12060: /*         } */
1.218     brouard  12061:            
1.227     brouard  12062: /*         if (h==(int)(calagedatem+12*cpt)) */
                   12063: /*           for(j=1; j<=nlstate;j++)  */
                   12064: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   12065: /*       } */
                   12066: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12067: /*     } */
                   12068: /*       } */
1.218     brouard  12069:       
1.227     brouard  12070: /*       /\******\/ */
1.218     brouard  12071:       
1.227     brouard  12072: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   12073: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   12074: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12075: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12076: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12077:          
1.227     brouard  12078: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12079: /*       oldm=oldms;savm=savms; */
                   12080: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12081: /*       for (h=0; h<=nhstepm; h++){ */
                   12082: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12083: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12084: /*         }  */
                   12085: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12086: /*           kk1=0.;kk2=0; */
                   12087: /*           for(i=1; i<=nlstate;i++) {               */
                   12088: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   12089: /*           } */
                   12090: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   12091: /*         } */
                   12092: /*       } */
                   12093: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12094: /*     } */
                   12095: /*       } */
                   12096: /*     }  */
                   12097: /*   } */
1.218     brouard  12098:   
1.227     brouard  12099: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  12100:   
1.227     brouard  12101: /*   if (popforecast==1) { */
                   12102: /*     free_ivector(popage,0,AGESUP); */
                   12103: /*     free_vector(popeffectif,0,AGESUP); */
                   12104: /*     free_vector(popcount,0,AGESUP); */
                   12105: /*   } */
                   12106: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12107: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12108: /*   fclose(ficrespop); */
                   12109: /* } /\* End of popforecast *\/ */
1.218     brouard  12110:  
1.126     brouard  12111: int fileappend(FILE *fichier, char *optionfich)
                   12112: {
                   12113:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   12114:     printf("Problem with file: %s\n", optionfich);
                   12115:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   12116:     return (0);
                   12117:   }
                   12118:   fflush(fichier);
                   12119:   return (1);
                   12120: }
                   12121: 
                   12122: 
                   12123: /**************** function prwizard **********************/
                   12124: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   12125: {
                   12126: 
                   12127:   /* Wizard to print covariance matrix template */
                   12128: 
1.164     brouard  12129:   char ca[32], cb[32];
                   12130:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  12131:   int numlinepar;
                   12132: 
                   12133:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12134:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12135:   for(i=1; i <=nlstate; i++){
                   12136:     jj=0;
                   12137:     for(j=1; j <=nlstate+ndeath; j++){
                   12138:       if(j==i) continue;
                   12139:       jj++;
                   12140:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   12141:       printf("%1d%1d",i,j);
                   12142:       fprintf(ficparo,"%1d%1d",i,j);
                   12143:       for(k=1; k<=ncovmodel;k++){
                   12144:        /*        printf(" %lf",param[i][j][k]); */
                   12145:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   12146:        printf(" 0.");
                   12147:        fprintf(ficparo," 0.");
                   12148:       }
                   12149:       printf("\n");
                   12150:       fprintf(ficparo,"\n");
                   12151:     }
                   12152:   }
                   12153:   printf("# Scales (for hessian or gradient estimation)\n");
                   12154:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   12155:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   12156:   for(i=1; i <=nlstate; i++){
                   12157:     jj=0;
                   12158:     for(j=1; j <=nlstate+ndeath; j++){
                   12159:       if(j==i) continue;
                   12160:       jj++;
                   12161:       fprintf(ficparo,"%1d%1d",i,j);
                   12162:       printf("%1d%1d",i,j);
                   12163:       fflush(stdout);
                   12164:       for(k=1; k<=ncovmodel;k++){
                   12165:        /*      printf(" %le",delti3[i][j][k]); */
                   12166:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   12167:        printf(" 0.");
                   12168:        fprintf(ficparo," 0.");
                   12169:       }
                   12170:       numlinepar++;
                   12171:       printf("\n");
                   12172:       fprintf(ficparo,"\n");
                   12173:     }
                   12174:   }
                   12175:   printf("# Covariance matrix\n");
                   12176: /* # 121 Var(a12)\n\ */
                   12177: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12178: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12179: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12180: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12181: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12182: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12183: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12184:   fflush(stdout);
                   12185:   fprintf(ficparo,"# Covariance matrix\n");
                   12186:   /* # 121 Var(a12)\n\ */
                   12187:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12188:   /* #   ...\n\ */
                   12189:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   12190:   
                   12191:   for(itimes=1;itimes<=2;itimes++){
                   12192:     jj=0;
                   12193:     for(i=1; i <=nlstate; i++){
                   12194:       for(j=1; j <=nlstate+ndeath; j++){
                   12195:        if(j==i) continue;
                   12196:        for(k=1; k<=ncovmodel;k++){
                   12197:          jj++;
                   12198:          ca[0]= k+'a'-1;ca[1]='\0';
                   12199:          if(itimes==1){
                   12200:            printf("#%1d%1d%d",i,j,k);
                   12201:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   12202:          }else{
                   12203:            printf("%1d%1d%d",i,j,k);
                   12204:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   12205:            /*  printf(" %.5le",matcov[i][j]); */
                   12206:          }
                   12207:          ll=0;
                   12208:          for(li=1;li <=nlstate; li++){
                   12209:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   12210:              if(lj==li) continue;
                   12211:              for(lk=1;lk<=ncovmodel;lk++){
                   12212:                ll++;
                   12213:                if(ll<=jj){
                   12214:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   12215:                  if(ll<jj){
                   12216:                    if(itimes==1){
                   12217:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12218:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12219:                    }else{
                   12220:                      printf(" 0.");
                   12221:                      fprintf(ficparo," 0.");
                   12222:                    }
                   12223:                  }else{
                   12224:                    if(itimes==1){
                   12225:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   12226:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   12227:                    }else{
                   12228:                      printf(" 0.");
                   12229:                      fprintf(ficparo," 0.");
                   12230:                    }
                   12231:                  }
                   12232:                }
                   12233:              } /* end lk */
                   12234:            } /* end lj */
                   12235:          } /* end li */
                   12236:          printf("\n");
                   12237:          fprintf(ficparo,"\n");
                   12238:          numlinepar++;
                   12239:        } /* end k*/
                   12240:       } /*end j */
                   12241:     } /* end i */
                   12242:   } /* end itimes */
                   12243: 
                   12244: } /* end of prwizard */
                   12245: /******************* Gompertz Likelihood ******************************/
                   12246: double gompertz(double x[])
                   12247: { 
1.302     brouard  12248:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  12249:   int i,n=0; /* n is the size of the sample */
                   12250: 
1.220     brouard  12251:   for (i=1;i<=imx ; i++) {
1.126     brouard  12252:     sump=sump+weight[i];
                   12253:     /*    sump=sump+1;*/
                   12254:     num=num+1;
                   12255:   }
1.302     brouard  12256:   L=0.0;
                   12257:   /* agegomp=AGEGOMP; */
1.126     brouard  12258:   /* for (i=0; i<=imx; i++) 
                   12259:      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]);*/
                   12260: 
1.302     brouard  12261:   for (i=1;i<=imx ; i++) {
                   12262:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   12263:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   12264:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   12265:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   12266:      * +
                   12267:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   12268:      */
                   12269:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   12270:        if (cens[i] == 1){
                   12271:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   12272:        } else if (cens[i] == 0){
1.126     brouard  12273:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  12274:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   12275:       } else
                   12276:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  12277:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  12278:        L=L+A*weight[i];
1.126     brouard  12279:        /*      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  12280:      }
                   12281:   }
1.126     brouard  12282: 
1.302     brouard  12283:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  12284:  
                   12285:   return -2*L*num/sump;
                   12286: }
                   12287: 
1.136     brouard  12288: #ifdef GSL
                   12289: /******************* Gompertz_f Likelihood ******************************/
                   12290: double gompertz_f(const gsl_vector *v, void *params)
                   12291: { 
1.302     brouard  12292:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  12293:   double *x= (double *) v->data;
                   12294:   int i,n=0; /* n is the size of the sample */
                   12295: 
                   12296:   for (i=0;i<=imx-1 ; i++) {
                   12297:     sump=sump+weight[i];
                   12298:     /*    sump=sump+1;*/
                   12299:     num=num+1;
                   12300:   }
                   12301:  
                   12302:  
                   12303:   /* for (i=0; i<=imx; i++) 
                   12304:      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]);*/
                   12305:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   12306:   for (i=1;i<=imx ; i++)
                   12307:     {
                   12308:       if (cens[i] == 1 && wav[i]>1)
                   12309:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   12310:       
                   12311:       if (cens[i] == 0 && wav[i]>1)
                   12312:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   12313:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   12314:       
                   12315:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   12316:       if (wav[i] > 1 ) { /* ??? */
                   12317:        LL=LL+A*weight[i];
                   12318:        /*      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]);*/
                   12319:       }
                   12320:     }
                   12321: 
                   12322:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   12323:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   12324:  
                   12325:   return -2*LL*num/sump;
                   12326: }
                   12327: #endif
                   12328: 
1.126     brouard  12329: /******************* Printing html file ***********/
1.201     brouard  12330: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  12331:                  int lastpass, int stepm, int weightopt, char model[],\
                   12332:                  int imx,  double p[],double **matcov,double agemortsup){
                   12333:   int i,k;
                   12334: 
                   12335:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   12336:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   12337:   for (i=1;i<=2;i++) 
                   12338:     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  12339:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  12340:   fprintf(fichtm,"</ul>");
                   12341: 
                   12342: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   12343: 
                   12344:  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>");
                   12345: 
                   12346:  for (k=agegomp;k<(agemortsup-2);k++) 
                   12347:    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]);
                   12348: 
                   12349:  
                   12350:   fflush(fichtm);
                   12351: }
                   12352: 
                   12353: /******************* Gnuplot file **************/
1.201     brouard  12354: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  12355: 
                   12356:   char dirfileres[132],optfileres[132];
1.164     brouard  12357: 
1.359     brouard  12358:   /*int ng;*/
1.126     brouard  12359: 
                   12360: 
                   12361:   /*#ifdef windows */
                   12362:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   12363:     /*#endif */
                   12364: 
                   12365: 
                   12366:   strcpy(dirfileres,optionfilefiname);
                   12367:   strcpy(optfileres,"vpl");
1.199     brouard  12368:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  12369:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  12370:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  12371:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  12372:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   12373: 
                   12374: } 
                   12375: 
1.136     brouard  12376: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   12377: {
1.126     brouard  12378: 
1.136     brouard  12379:   /*-------- data file ----------*/
                   12380:   FILE *fic;
                   12381:   char dummy[]="                         ";
1.359     brouard  12382:   int i = 0, j = 0, n = 0, iv = 0;/* , v;*/
1.223     brouard  12383:   int lstra;
1.136     brouard  12384:   int linei, month, year,iout;
1.302     brouard  12385:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  12386:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  12387:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  12388:   char *stratrunc;
1.223     brouard  12389: 
1.349     brouard  12390:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   12391:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  12392:   
                   12393:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   12394:   
1.136     brouard  12395:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  12396:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12397:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  12398:   }
1.126     brouard  12399: 
1.302     brouard  12400:     /* Is it a BOM UTF-8 Windows file? */
                   12401:   /* First data line */
                   12402:   linei=0;
                   12403:   while(fgets(line, MAXLINE, fic)) {
                   12404:     noffset=0;
                   12405:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12406:     {
                   12407:       noffset=noffset+3;
                   12408:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   12409:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   12410:       fflush(ficlog); return 1;
                   12411:     }
                   12412:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12413:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   12414:     {
                   12415:       noffset=noffset+2;
1.304     brouard  12416:       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);
                   12417:       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  12418:       fflush(ficlog); return 1;
                   12419:     }
                   12420:     else if( line[0] == 0 && line[1] == 0)
                   12421:     {
                   12422:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12423:        noffset=noffset+4;
1.304     brouard  12424:        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);
                   12425:        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  12426:        fflush(ficlog); return 1;
                   12427:       }
                   12428:     } else{
                   12429:       ;/*printf(" Not a BOM file\n");*/
                   12430:     }
                   12431:         /* If line starts with a # it is a comment */
                   12432:     if (line[noffset] == '#') {
                   12433:       linei=linei+1;
                   12434:       break;
                   12435:     }else{
                   12436:       break;
                   12437:     }
                   12438:   }
                   12439:   fclose(fic);
                   12440:   if((fic=fopen(datafile,"r"))==NULL)    {
                   12441:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12442:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   12443:   }
                   12444:   /* Not a Bom file */
                   12445:   
1.136     brouard  12446:   i=1;
                   12447:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   12448:     linei=linei+1;
                   12449:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   12450:       if(line[j] == '\t')
                   12451:        line[j] = ' ';
                   12452:     }
                   12453:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   12454:       ;
                   12455:     };
                   12456:     line[j+1]=0;  /* Trims blanks at end of line */
                   12457:     if(line[0]=='#'){
                   12458:       fprintf(ficlog,"Comment line\n%s\n",line);
                   12459:       printf("Comment line\n%s\n",line);
                   12460:       continue;
                   12461:     }
                   12462:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  12463:     strcpy(line, linetmp);
1.223     brouard  12464:     
                   12465:     /* Loops on waves */
                   12466:     for (j=maxwav;j>=1;j--){
                   12467:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  12468:        cutv(stra, strb, line, ' '); 
                   12469:        if(strb[0]=='.') { /* Missing value */
                   12470:          lval=-1;
                   12471:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  12472:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  12473:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   12474:            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);
                   12475:            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);
                   12476:            return 1;
                   12477:          }
                   12478:        }else{
                   12479:          errno=0;
                   12480:          /* what_kind_of_number(strb); */
                   12481:          dval=strtod(strb,&endptr); 
                   12482:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   12483:          /* if(strb != endptr && *endptr == '\0') */
                   12484:          /*    dval=dlval; */
                   12485:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12486:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12487:            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);
                   12488:            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);
                   12489:            return 1;
                   12490:          }
                   12491:          cotqvar[j][iv][i]=dval; 
1.341     brouard  12492:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  12493:        }
                   12494:        strcpy(line,stra);
1.223     brouard  12495:       }/* end loop ntqv */
1.225     brouard  12496:       
1.223     brouard  12497:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  12498:        cutv(stra, strb, line, ' '); 
                   12499:        if(strb[0]=='.') { /* Missing value */
                   12500:          lval=-1;
                   12501:        }else{
                   12502:          errno=0;
                   12503:          lval=strtol(strb,&endptr,10); 
                   12504:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   12505:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12506:            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);
                   12507:            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);
                   12508:            return 1;
                   12509:          }
                   12510:        }
                   12511:        if(lval <-1 || lval >1){
                   12512:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12513:  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  12514:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12515:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12516:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12517:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12518:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12519:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12520:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  12521:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12522:  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  12523:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12524:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12525:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12526:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12527:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12528:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12529:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  12530:          return 1;
                   12531:        }
1.341     brouard  12532:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  12533:        strcpy(line,stra);
1.223     brouard  12534:       }/* end loop ntv */
1.225     brouard  12535:       
1.223     brouard  12536:       /* Statuses  at wave */
1.137     brouard  12537:       cutv(stra, strb, line, ' '); 
1.223     brouard  12538:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  12539:        lval=-1;
1.136     brouard  12540:       }else{
1.238     brouard  12541:        errno=0;
                   12542:        lval=strtol(strb,&endptr,10); 
                   12543:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  12544:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   12545:          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);
                   12546:          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);
                   12547:          return 1;
                   12548:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  12549:          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);
                   12550:          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  12551:          return 1;
                   12552:        }
1.136     brouard  12553:       }
1.225     brouard  12554:       
1.136     brouard  12555:       s[j][i]=lval;
1.225     brouard  12556:       
1.223     brouard  12557:       /* Date of Interview */
1.136     brouard  12558:       strcpy(line,stra);
                   12559:       cutv(stra, strb,line,' ');
1.169     brouard  12560:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12561:       }
1.169     brouard  12562:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  12563:        month=99;
                   12564:        year=9999;
1.136     brouard  12565:       }else{
1.225     brouard  12566:        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);
                   12567:        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);
                   12568:        return 1;
1.136     brouard  12569:       }
                   12570:       anint[j][i]= (double) year; 
1.302     brouard  12571:       mint[j][i]= (double)month;
                   12572:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   12573:       /*       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]); */
                   12574:       /*       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]); */
                   12575:       /* } */
1.136     brouard  12576:       strcpy(line,stra);
1.223     brouard  12577:     } /* End loop on waves */
1.225     brouard  12578:     
1.223     brouard  12579:     /* Date of death */
1.136     brouard  12580:     cutv(stra, strb,line,' '); 
1.169     brouard  12581:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12582:     }
1.169     brouard  12583:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  12584:       month=99;
                   12585:       year=9999;
                   12586:     }else{
1.141     brouard  12587:       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  12588:       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);
                   12589:       return 1;
1.136     brouard  12590:     }
                   12591:     andc[i]=(double) year; 
                   12592:     moisdc[i]=(double) month; 
                   12593:     strcpy(line,stra);
                   12594:     
1.223     brouard  12595:     /* Date of birth */
1.136     brouard  12596:     cutv(stra, strb,line,' '); 
1.169     brouard  12597:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12598:     }
1.169     brouard  12599:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  12600:       month=99;
                   12601:       year=9999;
                   12602:     }else{
1.141     brouard  12603:       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);
                   12604:       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  12605:       return 1;
1.136     brouard  12606:     }
                   12607:     if (year==9999) {
1.141     brouard  12608:       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);
                   12609:       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  12610:       return 1;
                   12611:       
1.136     brouard  12612:     }
                   12613:     annais[i]=(double)(year);
1.302     brouard  12614:     moisnais[i]=(double)(month);
                   12615:     for (j=1;j<=maxwav;j++){
                   12616:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   12617:        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]);
                   12618:        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]);
                   12619:       }
                   12620:     }
                   12621: 
1.136     brouard  12622:     strcpy(line,stra);
1.225     brouard  12623:     
1.223     brouard  12624:     /* Sample weight */
1.136     brouard  12625:     cutv(stra, strb,line,' '); 
                   12626:     errno=0;
                   12627:     dval=strtod(strb,&endptr); 
                   12628:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  12629:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   12630:       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  12631:       fflush(ficlog);
                   12632:       return 1;
                   12633:     }
                   12634:     weight[i]=dval; 
                   12635:     strcpy(line,stra);
1.225     brouard  12636:     
1.223     brouard  12637:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   12638:       cutv(stra, strb, line, ' '); 
                   12639:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  12640:        lval=-1;
1.311     brouard  12641:        coqvar[iv][i]=NAN; 
                   12642:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12643:       }else{
1.225     brouard  12644:        errno=0;
                   12645:        /* what_kind_of_number(strb); */
                   12646:        dval=strtod(strb,&endptr);
                   12647:        /* if(strb != endptr && *endptr == '\0') */
                   12648:        /*   dval=dlval; */
                   12649:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12650:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12651:          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);
                   12652:          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);
                   12653:          return 1;
                   12654:        }
                   12655:        coqvar[iv][i]=dval; 
1.226     brouard  12656:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12657:       }
                   12658:       strcpy(line,stra);
                   12659:     }/* end loop nqv */
1.136     brouard  12660:     
1.223     brouard  12661:     /* Covariate values */
1.136     brouard  12662:     for (j=ncovcol;j>=1;j--){
                   12663:       cutv(stra, strb,line,' '); 
1.223     brouard  12664:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  12665:        lval=-1;
1.136     brouard  12666:       }else{
1.225     brouard  12667:        errno=0;
                   12668:        lval=strtol(strb,&endptr,10); 
                   12669:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12670:          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);
                   12671:          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);
                   12672:          return 1;
                   12673:        }
1.136     brouard  12674:       }
                   12675:       if(lval <-1 || lval >1){
1.225     brouard  12676:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12677:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12678:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12679:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12680:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12681:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12682:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12683:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12684:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  12685:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12686:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12687:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12688:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12689:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12690:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12691:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12692:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12693:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  12694:        return 1;
1.136     brouard  12695:       }
                   12696:       covar[j][i]=(double)(lval);
                   12697:       strcpy(line,stra);
                   12698:     }  
                   12699:     lstra=strlen(stra);
1.225     brouard  12700:     
1.136     brouard  12701:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   12702:       stratrunc = &(stra[lstra-9]);
                   12703:       num[i]=atol(stratrunc);
                   12704:     }
                   12705:     else
                   12706:       num[i]=atol(stra);
                   12707:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   12708:       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;}*/
                   12709:     
                   12710:     i=i+1;
                   12711:   } /* End loop reading  data */
1.225     brouard  12712:   
1.136     brouard  12713:   *imax=i-1; /* Number of individuals */
                   12714:   fclose(fic);
1.225     brouard  12715:   
1.136     brouard  12716:   return (0);
1.164     brouard  12717:   /* endread: */
1.225     brouard  12718:   printf("Exiting readdata: ");
                   12719:   fclose(fic);
                   12720:   return (1);
1.223     brouard  12721: }
1.126     brouard  12722: 
1.234     brouard  12723: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  12724:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  12725:   while (*p2 == ' ')
1.234     brouard  12726:     p2++; 
                   12727:   /* while ((*p1++ = *p2++) !=0) */
                   12728:   /*   ; */
                   12729:   /* do */
                   12730:   /*   while (*p2 == ' ') */
                   12731:   /*     p2++; */
                   12732:   /* while (*p1++ == *p2++); */
                   12733:   *stri=p2; 
1.145     brouard  12734: }
                   12735: 
1.330     brouard  12736: int decoderesult( char resultline[], int nres)
1.230     brouard  12737: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   12738: {
1.235     brouard  12739:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  12740:   char resultsav[MAXLINE];
1.330     brouard  12741:   /* int resultmodel[MAXLINE]; */
1.334     brouard  12742:   /* int modelresult[MAXLINE]; */
1.230     brouard  12743:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   12744: 
1.234     brouard  12745:   removefirstspace(&resultline);
1.332     brouard  12746:   printf("decoderesult:%s\n",resultline);
1.230     brouard  12747: 
1.332     brouard  12748:   strcpy(resultsav,resultline);
1.342     brouard  12749:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  12750:   if (strlen(resultsav) >1){
1.334     brouard  12751:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  12752:   }
1.353     brouard  12753:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  12754:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   12755:     return (0);
                   12756:   }
1.234     brouard  12757:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  12758:     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);
                   12759:     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);
                   12760:     if(j==0)
                   12761:       return 1;
1.234     brouard  12762:   }
1.334     brouard  12763:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  12764:     if(nbocc(resultsav,'=') >1){
1.318     brouard  12765:       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  12766:       /* 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  12767:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  12768:       /* If a blank, then strc="V4=" and strd='\0' */
                   12769:       if(strc[0]=='\0'){
                   12770:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   12771:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   12772:        return 1;
                   12773:       }
1.234     brouard  12774:     }else
                   12775:       cutl(strc,strd,resultsav,'=');
1.318     brouard  12776:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  12777:     
1.230     brouard  12778:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  12779:     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  12780:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   12781:     /* cptcovsel++;     */
                   12782:     if (nbocc(stra,'=') >0)
                   12783:       strcpy(resultsav,stra); /* and analyzes it */
                   12784:   }
1.235     brouard  12785:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12786:   /* 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  12787:   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  12788:     if(Typevar[k1]==0){ /* Single covariate in model */
                   12789:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  12790:       match=0;
1.318     brouard  12791:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12792:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12793:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  12794:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  12795:          break;
                   12796:        }
                   12797:       }
                   12798:       if(match == 0){
1.338     brouard  12799:        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]);
                   12800:        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  12801:        return 1;
1.234     brouard  12802:       }
1.332     brouard  12803:     }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*/
                   12804:       /* We feed resultmodel[k1]=k2; */
                   12805:       match=0;
                   12806:       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 */
                   12807:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12808:          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  12809:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  12810:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  12811:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12812:          break;
                   12813:        }
                   12814:       }
                   12815:       if(match == 0){
1.338     brouard  12816:        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]);
                   12817:        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  12818:       return 1;
                   12819:       }
1.349     brouard  12820:     }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  12821:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   12822:       match=0;
1.342     brouard  12823:       /* 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  12824:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12825:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12826:          /* modelresult[k2]=k1; */
1.342     brouard  12827:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  12828:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12829:        }
                   12830:       }
                   12831:       if(match == 0){
1.349     brouard  12832:        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);
                   12833:        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  12834:        return 1;
                   12835:       }
                   12836:       match=0;
                   12837:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12838:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12839:          /* modelresult[k2]=k1;*/
1.342     brouard  12840:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  12841:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12842:          break;
                   12843:        }
                   12844:       }
                   12845:       if(match == 0){
1.349     brouard  12846:        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);
                   12847:        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  12848:        return 1;
                   12849:       }
                   12850:     }/* End of testing */
1.333     brouard  12851:   }/* End loop cptcovt */
1.235     brouard  12852:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12853:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  12854:   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)
                   12855:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  12856:     match=0;
1.318     brouard  12857:     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  12858:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  12859:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  12860:          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  12861:          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  12862:          ++match;
                   12863:        }
                   12864:       }
                   12865:     }
                   12866:     if(match == 0){
1.338     brouard  12867:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   12868:       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  12869:       return 1;
1.234     brouard  12870:     }else if(match > 1){
1.338     brouard  12871:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   12872:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  12873:       return 1;
1.234     brouard  12874:     }
                   12875:   }
1.334     brouard  12876:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  12877:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  12878:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  12879:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   12880:   /* 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*/
                   12881:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  12882:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   12883:   /*    1 0 0 0 */
                   12884:   /*    2 1 0 0 */
                   12885:   /*    3 0 1 0 */ 
1.330     brouard  12886:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  12887:   /*    5 0 0 1 */
1.330     brouard  12888:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  12889:   /*    7 0 1 1 */
                   12890:   /*    8 1 1 1 */
1.237     brouard  12891:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   12892:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   12893:   /* V5*age V5 known which value for nres?  */
                   12894:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  12895:   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.
                   12896:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  12897:     /* k counting number of combination of single dummies in the equation model */
                   12898:     /* k4 counting single dummies in the equation model */
                   12899:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  12900:     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  12901:        /* 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  12902:       /* 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  12903:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  12904:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   12905:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   12906:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   12907:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   12908:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  12909:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  12910:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  12911:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  12912:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   12913:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12914:       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  12915:       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  12916:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  12917:       /* Tinvresult[nres][4]=1 */
1.334     brouard  12918:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   12919:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   12920:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12921:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  12922:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  12923:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  12924:       /* 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  12925:       k4++;;
1.331     brouard  12926:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  12927:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  12928:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  12929:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  12930:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   12931:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   12932:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  12933:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   12934:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12935:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   12936:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   12937:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   12938:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  12939:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  12940:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  12941:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  12942:       /* 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  12943:       k4q++;;
1.350     brouard  12944:     }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"*/
                   12945:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  12946:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  12947:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12948:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12949:       /* 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]]); */
                   12950:       }else{
                   12951:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12952:        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)*/
                   12953:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   12954:        precov[nres][k1]=Tvalsel[k3];
                   12955:       }
1.342     brouard  12956:       /* 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  12957:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  12958:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12959:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12960:       /* 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]]); */
                   12961:       }else{
                   12962:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   12963:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   12964:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   12965:        precov[nres][k1]=Tvalsel[k3q];
                   12966:       }
1.342     brouard  12967:       /* 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  12968:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  12969:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  12970:       /* 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  12971:     }else{
1.332     brouard  12972:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   12973:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  12974:     }
                   12975:   }
1.234     brouard  12976:   
1.334     brouard  12977:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  12978:   return (0);
                   12979: }
1.235     brouard  12980: 
1.230     brouard  12981: int decodemodel( char model[], int lastobs)
                   12982:  /**< This routine decodes the model and returns:
1.224     brouard  12983:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   12984:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   12985:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   12986:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   12987:        * - cptcovage number of covariates with age*products =2
                   12988:        * - cptcovs number of simple covariates
1.339     brouard  12989:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  12990:        * - 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  12991:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  12992:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  12993:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   12994:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   12995:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   12996:        */
1.319     brouard  12997: /* 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  12998: {
1.359     brouard  12999:   int i, j, k, ks;/* , v;*/
1.349     brouard  13000:   int n,m;
                   13001:   int  j1, k1, k11, k12, k2, k3, k4;
                   13002:   char modelsav[300];
                   13003:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  13004:   char *strpt;
1.349     brouard  13005:   int  **existcomb;
                   13006:   
                   13007:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   13008:   for(i=1;i<=NCOVMAX;i++)
                   13009:     for(j=1;j<=NCOVMAX;j++)
                   13010:       existcomb[i][j]=0;
                   13011:     
1.145     brouard  13012:   /*removespace(model);*/
1.136     brouard  13013:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  13014:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  13015:     if (strstr(model,"AGE") !=0){
1.192     brouard  13016:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   13017:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  13018:       return 1;
                   13019:     }
1.141     brouard  13020:     if (strstr(model,"v") !=0){
1.338     brouard  13021:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   13022:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  13023:       return 1;
                   13024:     }
1.187     brouard  13025:     strcpy(modelsav,model); 
                   13026:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  13027:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  13028:       if(strpt != model){
1.338     brouard  13029:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13030:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13031:  corresponding column of parameters.\n",model);
1.338     brouard  13032:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13033:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13034:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  13035:        return 1;
1.225     brouard  13036:       }
1.187     brouard  13037:       nagesqr=1;
                   13038:       if (strstr(model,"+age*age") !=0)
1.234     brouard  13039:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  13040:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  13041:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  13042:       else 
1.234     brouard  13043:        substrchaine(modelsav, model, "age*age");
1.187     brouard  13044:     }else
                   13045:       nagesqr=0;
1.349     brouard  13046:     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  13047:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   13048:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  13049:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  13050:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  13051:                     * cst, age and age*age 
                   13052:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   13053:       /* including age products which are counted in cptcovage.
                   13054:        * but the covariates which are products must be treated 
                   13055:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  13056:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   13057:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  13058:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  13059:       cptcovprodage=0;
                   13060:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  13061:       
1.187     brouard  13062:       /*   Design
                   13063:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   13064:        *  <          ncovcol=8                >
                   13065:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   13066:        *   k=  1    2      3       4     5       6      7        8
                   13067:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  13068:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  13069:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   13070:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  13071:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   13072:        *  Tage[++cptcovage]=k
1.345     brouard  13073:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  13074:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   13075:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   13076:        *  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
                   13077:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   13078:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   13079:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  13080:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  13081:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   13082:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  13083:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   13084:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  13085:        * p Tprod[1]@2={                         6, 5}
                   13086:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   13087:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   13088:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  13089:        *How to reorganize? Tvars(orted)
1.187     brouard  13090:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   13091:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   13092:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   13093:        * Struct []
                   13094:        */
1.225     brouard  13095:       
1.187     brouard  13096:       /* This loop fills the array Tvar from the string 'model'.*/
                   13097:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   13098:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   13099:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   13100:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   13101:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   13102:       /*       k=1 Tvar[1]=2 (from V2) */
                   13103:       /*       k=5 Tvar[5] */
                   13104:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  13105:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  13106:       /*       } */
1.198     brouard  13107:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  13108:       /*
                   13109:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  13110:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   13111:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   13112:       }
1.187     brouard  13113:       cptcovage=0;
1.351     brouard  13114: 
                   13115:       /* First loop in order to calculate */
                   13116:       /* for age*VN*Vm
                   13117:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   13118:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   13119:       */
                   13120:       /* Needs  FixedV[Tvardk[k][1]] */
                   13121:       /* For others:
                   13122:        * Sets  Typevar[k];
                   13123:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13124:        *       Tposprod[k]=k11;
                   13125:        *       Tprod[k11]=k;
                   13126:        *       Tvardk[k][1] =m;
                   13127:        * Needs FixedV[Tvardk[k][1]] == 0
                   13128:       */
                   13129:       
1.319     brouard  13130:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   13131:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   13132:                                         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" */
                   13133:        if (nbocc(modelsav,'+')==0)
                   13134:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  13135:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   13136:        /*scanf("%d",i);*/
1.349     brouard  13137:        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 */
                   13138:          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  */
                   13139:          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   */
                   13140:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   13141:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   13142:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   13143:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   13144:              /* We want strb=Vn*Vm */
                   13145:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   13146:                 strcpy(strb,strd);
                   13147:                 strcat(strb,"*");
                   13148:                 strcat(strb,stre);
                   13149:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   13150:                 strcpy(strb,strf);
                   13151:                 strcat(strb,"*");
                   13152:                 strcat(strb,stre);
                   13153:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   13154:               }
1.351     brouard  13155:              /* 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]]]); */
                   13156:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  13157:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   13158:              strcpy(stre,strb); /* save full b in stre */
                   13159:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   13160:              strcpy(strf,strc); /* save short c in new short f */
                   13161:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   13162:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   13163:             }
                   13164:             cptcovdageprod++; /* double product with age  Which product is it? */
                   13165:             /* 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 *\/ */
                   13166:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  13167:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  13168:            n=atoi(stre);
1.234     brouard  13169:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  13170:            m=atoi(strc);
                   13171:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   13172:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   13173:            if(existcomb[n][m] == 0){
                   13174:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   13175:              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);
                   13176:              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);
                   13177:              fflush(ficlog);
                   13178:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   13179:              k12++;
                   13180:              existcomb[n][m]=k1;
                   13181:              existcomb[m][n]=k1;
                   13182:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   13183:              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*/
                   13184:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   13185:              Tvard[k1][1] =m; /* m 1 for V1*/
                   13186:              Tvardk[k][1] =m; /* m 1 for V1*/
                   13187:              Tvard[k1][2] =n; /* n 4 for V4*/
                   13188:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  13189: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  13190:              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 */
                   13191:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   13192:                  /* Computes the new covariate which is a product of
                   13193:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13194:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13195:                }
                   13196:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13197:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13198:                k12++;
                   13199:                FixedV[ncovcolt+k12]=0;
                   13200:              }else{ /*End of FixedV */
                   13201:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   13202:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13203:                k12++;
                   13204:                FixedV[ncovcolt+k12]=1;
                   13205:              }
                   13206:            }else{  /* k1 Vn*Vm already exists */
                   13207:              k11=existcomb[n][m];
                   13208:              Tposprod[k]=k11; /* OK */
                   13209:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   13210:              Tvardk[k][1]=m;
                   13211:              Tvardk[k][2]=n;
                   13212:              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 */
                   13213:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13214:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13215:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13216:                Tvar[Tage[cptcovage]]=k1;
                   13217:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13218:                k12++;
                   13219:                FixedV[ncovcolt+k12]=0;
                   13220:              }else{ /* Already exists but time varying (and age) */
                   13221:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13222:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13223:                /* Tvar[Tage[cptcovage]]=k1; */
                   13224:                cptcovprodvage++;
                   13225:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13226:                k12++;
                   13227:                FixedV[ncovcolt+k12]=1;
                   13228:              }
                   13229:            }
                   13230:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   13231:            /* Tvar[k]=k11; /\* HERY *\/ */
                   13232:          } 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 */
                   13233:             cptcovprod++;
                   13234:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   13235:               /* covar is not filled and then is empty */
                   13236:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   13237:               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 */
                   13238:               Typevar[k]=1;  /* 1 for age product */
                   13239:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   13240:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   13241:              if( FixedV[Tvar[k]] == 0){
                   13242:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13243:              }else{
                   13244:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   13245:              }
                   13246:               /*printf("stre=%s ", stre);*/
                   13247:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   13248:               cutl(stre,strb,strc,'V');
                   13249:               Tvar[k]=atoi(stre);
                   13250:               Typevar[k]=1;  /* 1 for age product */
                   13251:               cptcovage++;
                   13252:               Tage[cptcovage]=k;
                   13253:              if( FixedV[Tvar[k]] == 0){
                   13254:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13255:              }else{
                   13256:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  13257:              }
1.349     brouard  13258:             }else{ /*  for product Vn*Vm */
                   13259:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   13260:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   13261:              n=atoi(stre);
                   13262:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   13263:              m=atoi(strc);
                   13264:              k1++;
                   13265:              cptcovprodnoage++;
                   13266:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   13267:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13268:                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]);
                   13269:                fflush(ficlog);
                   13270:                k11=existcomb[n][m];
                   13271:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13272:                Tposprod[k]=k11;
                   13273:                Tprod[k11]=k;
                   13274:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13275:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   13276:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   13277:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   13278:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   13279:                existcomb[n][m]=k1;
                   13280:                existcomb[m][n]=k1;
                   13281:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   13282:                                                    because this model-covariate is a construction we invent a new column
                   13283:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   13284:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   13285:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   13286:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   13287:                /* Please remark that the new variables are model dependent */
                   13288:                /* If we have 4 variable but the model uses only 3, like in
                   13289:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   13290:                 *  k=     1     2      3   4     5        6        7       8
                   13291:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   13292:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   13293:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   13294:                 */
                   13295:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   13296:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   13297:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   13298:                Tvard[k1][1] =m; /* m 1 for V1*/
                   13299:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13300:                Tvard[k1][2] =n; /* n 4 for V4*/
                   13301:                Tvardk[k][2] =n; /* n 4 for V4*/
                   13302:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   13303:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   13304:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   13305:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   13306:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   13307:                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 */
                   13308:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   13309:                    /* Computes the new covariate which is a product of
                   13310:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13311:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13312:                  }
                   13313:                  /* TvarVV[k2]=n; */
                   13314:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13315:                  /* TvarVV[k2+1]=m; */
                   13316:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13317:                }else{ /* not FixedV */
                   13318:                  /* TvarVV[k2]=n; */
                   13319:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13320:                  /* TvarVV[k2+1]=m; */
                   13321:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13322:                }                 
                   13323:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   13324:            } /*  End of product Vn*Vm */
                   13325:           } /* End of age*double product or simple product */
                   13326:        }else { /* not a product */
1.234     brouard  13327:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   13328:          /*  scanf("%d",i);*/
                   13329:          cutl(strd,strc,strb,'V');
                   13330:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   13331:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   13332:          Tvar[k]=atoi(strd);
                   13333:          Typevar[k]=0;  /* 0 for simple covariates */
                   13334:        }
                   13335:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  13336:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  13337:                                  scanf("%d",i);*/
1.187     brouard  13338:       } /* end of loop + on total covariates */
1.351     brouard  13339: 
                   13340:       
1.187     brouard  13341:     } /* end if strlen(modelsave == 0) age*age might exist */
                   13342:   } /* end if strlen(model == 0) */
1.349     brouard  13343:   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  */
                   13344: 
1.136     brouard  13345:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   13346:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  13347:   
1.136     brouard  13348:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  13349:      printf("cptcovprod=%d ", cptcovprod);
                   13350:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   13351:      scanf("%d ",i);*/
                   13352: 
                   13353: 
1.230     brouard  13354: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   13355:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  13356: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   13357:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   13358:    k =           1    2   3     4       5       6      7      8        9
                   13359:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  13360:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  13361:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   13362:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   13363:          Tmodelind[combination of covar]=k;
1.225     brouard  13364: */  
                   13365: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  13366:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  13367:   /* 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  13368:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  13369:   printf("Model=1+age+%s\n\
1.349     brouard  13370: 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  13371: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13372: 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  13373:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  13374: 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  13375: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13376: 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  13377:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   13378:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  13379: 
                   13380: 
                   13381:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   13382: 
                   13383:   
1.349     brouard  13384:   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  13385:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  13386:       Fixed[k]= 0;
                   13387:       Dummy[k]= 0;
1.225     brouard  13388:       ncoveff++;
1.232     brouard  13389:       ncovf++;
1.234     brouard  13390:       nsd++;
                   13391:       modell[k].maintype= FTYPE;
                   13392:       TvarsD[nsd]=Tvar[k];
                   13393:       TvarsDind[nsd]=k;
1.330     brouard  13394:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  13395:       TvarF[ncovf]=Tvar[k];
                   13396:       TvarFind[ncovf]=k;
                   13397:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13398:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  13399:     /* }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  13400:     }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  13401:       Fixed[k]= 0;
                   13402:       Dummy[k]= 1;
1.230     brouard  13403:       nqfveff++;
1.234     brouard  13404:       modell[k].maintype= FTYPE;
                   13405:       modell[k].subtype= FQ;
                   13406:       nsq++;
1.334     brouard  13407:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   13408:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  13409:       ncovf++;
1.234     brouard  13410:       TvarF[ncovf]=Tvar[k];
                   13411:       TvarFind[ncovf]=k;
1.231     brouard  13412:       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  13413:       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  13414:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  13415:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13416:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13417:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13418:       ncovvt++;
                   13419:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13420:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   13421: 
1.227     brouard  13422:       Fixed[k]= 1;
                   13423:       Dummy[k]= 0;
1.225     brouard  13424:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  13425:       modell[k].maintype= VTYPE;
                   13426:       modell[k].subtype= VD;
                   13427:       nsd++;
                   13428:       TvarsD[nsd]=Tvar[k];
                   13429:       TvarsDind[nsd]=k;
1.330     brouard  13430:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  13431:       ncovv++; /* Only simple time varying variables */
                   13432:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13433:       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  13434:       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 */
                   13435:       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  13436:       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);
                   13437:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  13438:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  13439:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13440:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13441:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13442:       ncovvt++;
                   13443:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13444:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13445:       
1.234     brouard  13446:       Fixed[k]= 1;
                   13447:       Dummy[k]= 1;
                   13448:       nqtveff++;
                   13449:       modell[k].maintype= VTYPE;
                   13450:       modell[k].subtype= VQ;
                   13451:       ncovv++; /* Only simple time varying variables */
                   13452:       nsq++;
1.334     brouard  13453:       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) */
                   13454:       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  13455:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13456:       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  13457:       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 */
                   13458:       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  13459:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   13460:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  13461:       /* 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  13462:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  13463:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  13464:       ncova++;
                   13465:       TvarA[ncova]=Tvar[k];
                   13466:       TvarAind[ncova]=k;
1.349     brouard  13467:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13468:       /** 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  13469:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  13470:        Fixed[k]= 2;
                   13471:        Dummy[k]= 2;
                   13472:        modell[k].maintype= ATYPE;
                   13473:        modell[k].subtype= APFD;
1.349     brouard  13474:        ncovta++;
                   13475:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   13476:        TvarAVVAind[ncovta]=k;
1.240     brouard  13477:        /* ncoveff++; */
1.227     brouard  13478:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  13479:        Fixed[k]= 2;
                   13480:        Dummy[k]= 3;
                   13481:        modell[k].maintype= ATYPE;
                   13482:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  13483:        ncovta++;
                   13484:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13485:        TvarAVVAind[ncovta]=k;
1.240     brouard  13486:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  13487:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  13488:        Fixed[k]= 3;
                   13489:        Dummy[k]= 2;
                   13490:        modell[k].maintype= ATYPE;
                   13491:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  13492:        ncovva++;
                   13493:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13494:        TvarVVAind[ncovva]=k;
                   13495:        ncovta++;
                   13496:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13497:        TvarAVVAind[ncovta]=k;
1.240     brouard  13498:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  13499:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  13500:        Fixed[k]= 3;
                   13501:        Dummy[k]= 3;
                   13502:        modell[k].maintype= ATYPE;
                   13503:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  13504:        ncovva++;
                   13505:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   13506:        TvarVVAind[ncovva]=k;
                   13507:        ncovta++;
                   13508:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13509:        TvarAVVAind[ncovta]=k;
1.240     brouard  13510:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  13511:       }
1.349     brouard  13512:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   13513:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   13514:       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 */
                   13515:       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]]);
                   13516:        Fixed[k]= 0;
                   13517:        Dummy[k]= 0;
                   13518:        ncoveff++;
                   13519:        ncovf++;
                   13520:        /* ncovv++; */
                   13521:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   13522:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13523:        /* ncovv++; */
                   13524:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   13525:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13526:        modell[k].maintype= FTYPE;
                   13527:        TvarF[ncovf]=Tvar[k];
                   13528:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   13529:        TvarFind[ncovf]=k;
                   13530:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13531:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13532:       }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  */
                   13533:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13534:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13535:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13536:        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 */
                   13537:        ncovvt++;
                   13538:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13539:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13540:        ncovvt++;
                   13541:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13542:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13543:        
                   13544:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13545:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13546:        
                   13547:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13548:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   13549:            Fixed[k]= 1;
                   13550:            Dummy[k]= 0;
                   13551:            modell[k].maintype= FTYPE;
                   13552:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   13553:            ncovf++; /* Fixed variables without age */
                   13554:            TvarF[ncovf]=Tvar[k];
                   13555:            TvarFind[ncovf]=k;
                   13556:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   13557:            Fixed[k]= 0;  /* Fixed product */
                   13558:            Dummy[k]= 1;
                   13559:            modell[k].maintype= FTYPE;
                   13560:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   13561:            ncovf++; /* Varying variables without age */
                   13562:            TvarF[ncovf]=Tvar[k];
                   13563:            TvarFind[ncovf]=k;
                   13564:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   13565:            Fixed[k]= 1;
                   13566:            Dummy[k]= 0;
                   13567:            modell[k].maintype= VTYPE;
                   13568:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   13569:            ncovv++; /* Varying variables without age */
                   13570:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13571:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   13572:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   13573:            Fixed[k]= 1;
                   13574:            Dummy[k]= 1;
                   13575:            modell[k].maintype= VTYPE;
                   13576:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   13577:            ncovv++; /* Varying variables without age */
                   13578:            TvarV[ncovv]=Tvar[k];
                   13579:            TvarVind[ncovv]=k;
                   13580:          }
                   13581:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13582:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   13583:            Fixed[k]= 0;  /*  Fixed product */
                   13584:            Dummy[k]= 1;
                   13585:            modell[k].maintype= FTYPE;
                   13586:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   13587:            ncovf++; /* Fixed variables without age */
                   13588:            TvarF[ncovf]=Tvar[k];
                   13589:            TvarFind[ncovf]=k;
                   13590:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   13591:            Fixed[k]= 1;
                   13592:            Dummy[k]= 1;
                   13593:            modell[k].maintype= VTYPE;
                   13594:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   13595:            ncovv++; /* Varying variables without age */
                   13596:            TvarV[ncovv]=Tvar[k];
                   13597:            TvarVind[ncovv]=k;
                   13598:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   13599:            Fixed[k]= 1;
                   13600:            Dummy[k]= 1;
                   13601:            modell[k].maintype= VTYPE;
                   13602:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   13603:            ncovv++; /* Varying variables without age */
                   13604:            TvarV[ncovv]=Tvar[k];
                   13605:            TvarVind[ncovv]=k;
                   13606:            ncovv++; /* Varying variables without age */
                   13607:            TvarV[ncovv]=Tvar[k];
                   13608:            TvarVind[ncovv]=k;
                   13609:          }
                   13610:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   13611:          if(Tvard[k1][2] <=ncovcol){
                   13612:            Fixed[k]= 1;
                   13613:            Dummy[k]= 1;
                   13614:            modell[k].maintype= VTYPE;
                   13615:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   13616:            ncovv++; /* Varying variables without age */
                   13617:            TvarV[ncovv]=Tvar[k];
                   13618:            TvarVind[ncovv]=k;
                   13619:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13620:            Fixed[k]= 1;
                   13621:            Dummy[k]= 1;
                   13622:            modell[k].maintype= VTYPE;
                   13623:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   13624:            ncovv++; /* Varying variables without age */
                   13625:            TvarV[ncovv]=Tvar[k];
                   13626:            TvarVind[ncovv]=k;
                   13627:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13628:            Fixed[k]= 1;
                   13629:            Dummy[k]= 0;
                   13630:            modell[k].maintype= VTYPE;
                   13631:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   13632:            ncovv++; /* Varying variables without age */
                   13633:            TvarV[ncovv]=Tvar[k];
                   13634:            TvarVind[ncovv]=k;
                   13635:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13636:            Fixed[k]= 1;
                   13637:            Dummy[k]= 1;
                   13638:            modell[k].maintype= VTYPE;
                   13639:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   13640:            ncovv++; /* Varying variables without age */
                   13641:            TvarV[ncovv]=Tvar[k];
                   13642:            TvarVind[ncovv]=k;
                   13643:          }
                   13644:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   13645:          if(Tvard[k1][2] <=ncovcol){
                   13646:            Fixed[k]= 1;
                   13647:            Dummy[k]= 1;
                   13648:            modell[k].maintype= VTYPE;
                   13649:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   13650:            ncovv++; /* Varying variables without age */
                   13651:            TvarV[ncovv]=Tvar[k];
                   13652:            TvarVind[ncovv]=k;
                   13653:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13654:            Fixed[k]= 1;
                   13655:            Dummy[k]= 1;
                   13656:            modell[k].maintype= VTYPE;
                   13657:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   13658:            ncovv++; /* Varying variables without age */
                   13659:            TvarV[ncovv]=Tvar[k];
                   13660:            TvarVind[ncovv]=k;
                   13661:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13662:            Fixed[k]= 1;
                   13663:            Dummy[k]= 1;
                   13664:            modell[k].maintype= VTYPE;
                   13665:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   13666:            ncovv++; /* Varying variables without age */
                   13667:            TvarV[ncovv]=Tvar[k];
                   13668:            TvarVind[ncovv]=k;
                   13669:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13670:            Fixed[k]= 1;
                   13671:            Dummy[k]= 1;
                   13672:            modell[k].maintype= VTYPE;
                   13673:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   13674:            ncovv++; /* Varying variables without age */
                   13675:            TvarV[ncovv]=Tvar[k];
                   13676:            TvarVind[ncovv]=k;
                   13677:          }
                   13678:        }else{
                   13679:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13680:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13681:        } /*end k1*/
                   13682:       }
                   13683:     }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  13684:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  13685:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13686:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13687:       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 */
                   13688:       ncova++;
                   13689:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13690:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13691:       ncova++;
                   13692:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13693:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  13694: 
1.349     brouard  13695:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13696:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13697:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   13698:        ncovta++;
                   13699:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13700:        TvarAVVAind[ncovta]=k;
                   13701:        ncovta++;
                   13702:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13703:        TvarAVVAind[ncovta]=k;
                   13704:       }else{
                   13705:        ncovva++;  /* HERY  reached */
                   13706:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   13707:        TvarVVAind[ncovva]=k;
                   13708:        ncovva++;
                   13709:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   13710:        TvarVVAind[ncovva]=k;
                   13711:        ncovta++;
                   13712:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13713:        TvarAVVAind[ncovta]=k;
                   13714:        ncovta++;
                   13715:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13716:        TvarAVVAind[ncovta]=k;
                   13717:       }
1.339     brouard  13718:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13719:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  13720:          Fixed[k]= 2;
                   13721:          Dummy[k]= 2;
1.240     brouard  13722:          modell[k].maintype= FTYPE;
                   13723:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  13724:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   13725:          /* TvarFind[ncova]=k; */
1.339     brouard  13726:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  13727:          Fixed[k]= 2;  /* Fixed product */
                   13728:          Dummy[k]= 3;
1.240     brouard  13729:          modell[k].maintype= FTYPE;
                   13730:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  13731:          /* TvarF[ncova]=Tvar[k]; */
                   13732:          /* TvarFind[ncova]=k; */
1.339     brouard  13733:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  13734:          Fixed[k]= 3;
                   13735:          Dummy[k]= 2;
1.240     brouard  13736:          modell[k].maintype= VTYPE;
                   13737:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  13738:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13739:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  13740:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  13741:          Fixed[k]= 3;
                   13742:          Dummy[k]= 3;
1.240     brouard  13743:          modell[k].maintype= VTYPE;
                   13744:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  13745:          /* ncovv++; /\* Varying variables without age *\/ */
                   13746:          /* TvarV[ncovv]=Tvar[k]; */
                   13747:          /* TvarVind[ncovv]=k; */
1.240     brouard  13748:        }
1.339     brouard  13749:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13750:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  13751:          Fixed[k]= 2;  /*  Fixed product */
                   13752:          Dummy[k]= 2;
1.240     brouard  13753:          modell[k].maintype= FTYPE;
                   13754:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  13755:          /* ncova++; /\* Fixed variables with age *\/ */
                   13756:          /* TvarF[ncovf]=Tvar[k]; */
                   13757:          /* TvarFind[ncovf]=k; */
1.339     brouard  13758:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  13759:          Fixed[k]= 2;
                   13760:          Dummy[k]= 3;
1.240     brouard  13761:          modell[k].maintype= VTYPE;
                   13762:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  13763:          /* ncova++; /\* Varying variables with age *\/ */
                   13764:          /* TvarV[ncova]=Tvar[k]; */
                   13765:          /* TvarVind[ncova]=k; */
1.339     brouard  13766:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  13767:          Fixed[k]= 3;
                   13768:          Dummy[k]= 2;
1.240     brouard  13769:          modell[k].maintype= VTYPE;
                   13770:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  13771:          ncova++; /* Varying variables without age */
                   13772:          TvarV[ncova]=Tvar[k];
                   13773:          TvarVind[ncova]=k;
                   13774:          /* ncova++; /\* Varying variables without age *\/ */
                   13775:          /* TvarV[ncova]=Tvar[k]; */
                   13776:          /* TvarVind[ncova]=k; */
1.240     brouard  13777:        }
1.339     brouard  13778:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  13779:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13780:          Fixed[k]= 2;
                   13781:          Dummy[k]= 2;
1.240     brouard  13782:          modell[k].maintype= VTYPE;
                   13783:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  13784:          /* ncova++; /\* Varying variables with age *\/ */
                   13785:          /* TvarV[ncova]=Tvar[k]; */
                   13786:          /* TvarVind[ncova]=k; */
1.240     brouard  13787:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13788:          Fixed[k]= 2;
                   13789:          Dummy[k]= 3;
1.240     brouard  13790:          modell[k].maintype= VTYPE;
                   13791:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  13792:          /* ncova++; /\* Varying variables with age *\/ */
                   13793:          /* TvarV[ncova]=Tvar[k]; */
                   13794:          /* TvarVind[ncova]=k; */
1.240     brouard  13795:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13796:          Fixed[k]= 3;
                   13797:          Dummy[k]= 2;
1.240     brouard  13798:          modell[k].maintype= VTYPE;
                   13799:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  13800:          /* ncova++; /\* Varying variables with age *\/ */
                   13801:          /* TvarV[ncova]=Tvar[k]; */
                   13802:          /* TvarVind[ncova]=k; */
1.240     brouard  13803:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13804:          Fixed[k]= 3;
                   13805:          Dummy[k]= 3;
1.240     brouard  13806:          modell[k].maintype= VTYPE;
                   13807:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  13808:          /* ncova++; /\* Varying variables with age *\/ */
                   13809:          /* TvarV[ncova]=Tvar[k]; */
                   13810:          /* TvarVind[ncova]=k; */
1.240     brouard  13811:        }
1.339     brouard  13812:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  13813:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13814:          Fixed[k]= 2;
                   13815:          Dummy[k]= 2;
1.240     brouard  13816:          modell[k].maintype= VTYPE;
                   13817:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  13818:          /* ncova++; /\* Varying variables with age *\/ */
                   13819:          /* TvarV[ncova]=Tvar[k]; */
                   13820:          /* TvarVind[ncova]=k; */
1.240     brouard  13821:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13822:          Fixed[k]= 2;
                   13823:          Dummy[k]= 3;
1.240     brouard  13824:          modell[k].maintype= VTYPE;
                   13825:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  13826:          /* ncova++; /\* Varying variables with age *\/ */
                   13827:          /* TvarV[ncova]=Tvar[k]; */
                   13828:          /* TvarVind[ncova]=k; */
1.240     brouard  13829:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13830:          Fixed[k]= 3;
                   13831:          Dummy[k]= 2;
1.240     brouard  13832:          modell[k].maintype= VTYPE;
                   13833:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  13834:          /* ncova++; /\* Varying variables with age *\/ */
                   13835:          /* TvarV[ncova]=Tvar[k]; */
                   13836:          /* TvarVind[ncova]=k; */
1.240     brouard  13837:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13838:          Fixed[k]= 3;
                   13839:          Dummy[k]= 3;
1.240     brouard  13840:          modell[k].maintype= VTYPE;
                   13841:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  13842:          /* ncova++; /\* Varying variables with age *\/ */
                   13843:          /* TvarV[ncova]=Tvar[k]; */
                   13844:          /* TvarVind[ncova]=k; */
1.240     brouard  13845:        }
1.227     brouard  13846:       }else{
1.240     brouard  13847:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13848:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13849:       } /*end k1*/
1.349     brouard  13850:     } else{
1.226     brouard  13851:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   13852:       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  13853:     }
1.342     brouard  13854:     /* 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]); */
                   13855:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  13856:     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]);
                   13857:   }
1.349     brouard  13858:   ncovvta=ncovva;
1.227     brouard  13859:   /* Searching for doublons in the model */
                   13860:   for(k1=1; k1<= cptcovt;k1++){
                   13861:     for(k2=1; k2 <k1;k2++){
1.285     brouard  13862:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   13863:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  13864:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   13865:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  13866:            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]);
                   13867:            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  13868:            return(1);
                   13869:          }
                   13870:        }else if (Typevar[k1] ==2){
                   13871:          k3=Tposprod[k1];
                   13872:          k4=Tposprod[k2];
                   13873:          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  13874:            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]]);
                   13875:            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  13876:            return(1);
                   13877:          }
                   13878:        }
1.227     brouard  13879:       }
                   13880:     }
1.225     brouard  13881:   }
                   13882:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   13883:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  13884:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   13885:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  13886: 
                   13887:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  13888:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  13889:   /*endread:*/
1.225     brouard  13890:   printf("Exiting decodemodel: ");
                   13891:   return (1);
1.136     brouard  13892: }
                   13893: 
1.169     brouard  13894: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  13895: {/* Check ages at death */
1.136     brouard  13896:   int i, m;
1.218     brouard  13897:   int firstone=0;
                   13898:   
1.136     brouard  13899:   for (i=1; i<=imx; i++) {
                   13900:     for(m=2; (m<= maxwav); m++) {
                   13901:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   13902:        anint[m][i]=9999;
1.216     brouard  13903:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   13904:          s[m][i]=-1;
1.136     brouard  13905:       }
                   13906:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  13907:        *nberr = *nberr + 1;
1.218     brouard  13908:        if(firstone == 0){
                   13909:          firstone=1;
1.260     brouard  13910:        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  13911:        }
1.262     brouard  13912:        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  13913:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  13914:       }
                   13915:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  13916:        (*nberr)++;
1.259     brouard  13917:        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  13918:        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  13919:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  13920:       }
                   13921:     }
                   13922:   }
                   13923: 
                   13924:   for (i=1; i<=imx; i++)  {
                   13925:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   13926:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  13927:       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  13928:        if (s[m][i] >= nlstate+1) {
1.169     brouard  13929:          if(agedc[i]>0){
                   13930:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  13931:              agev[m][i]=agedc[i];
1.214     brouard  13932:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  13933:            }else {
1.136     brouard  13934:              if ((int)andc[i]!=9999){
                   13935:                nbwarn++;
                   13936:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   13937:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   13938:                agev[m][i]=-1;
                   13939:              }
                   13940:            }
1.169     brouard  13941:          } /* agedc > 0 */
1.214     brouard  13942:        } /* end if */
1.136     brouard  13943:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   13944:                                 years but with the precision of a month */
                   13945:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   13946:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   13947:            agev[m][i]=1;
                   13948:          else if(agev[m][i] < *agemin){ 
                   13949:            *agemin=agev[m][i];
                   13950:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   13951:          }
                   13952:          else if(agev[m][i] >*agemax){
                   13953:            *agemax=agev[m][i];
1.156     brouard  13954:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  13955:          }
                   13956:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   13957:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  13958:        } /* en if 9*/
1.136     brouard  13959:        else { /* =9 */
1.214     brouard  13960:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  13961:          agev[m][i]=1;
                   13962:          s[m][i]=-1;
                   13963:        }
                   13964:       }
1.214     brouard  13965:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  13966:        agev[m][i]=1;
1.214     brouard  13967:       else{
                   13968:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   13969:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   13970:        agev[m][i]=0;
                   13971:       }
                   13972:     } /* End for lastpass */
                   13973:   }
1.136     brouard  13974:     
                   13975:   for (i=1; i<=imx; i++)  {
                   13976:     for(m=firstpass; (m<=lastpass); m++){
                   13977:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  13978:        (*nberr)++;
1.136     brouard  13979:        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);     
                   13980:        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);     
                   13981:        return 1;
                   13982:       }
                   13983:     }
                   13984:   }
                   13985: 
                   13986:   /*for (i=1; i<=imx; i++){
                   13987:   for (m=firstpass; (m<lastpass); m++){
                   13988:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   13989: }
                   13990: 
                   13991: }*/
                   13992: 
                   13993: 
1.139     brouard  13994:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   13995:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  13996: 
                   13997:   return (0);
1.164     brouard  13998:  /* endread:*/
1.136     brouard  13999:     printf("Exiting calandcheckages: ");
                   14000:     return (1);
                   14001: }
                   14002: 
1.172     brouard  14003: #if defined(_MSC_VER)
                   14004: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14005: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14006: //#include "stdafx.h"
                   14007: //#include <stdio.h>
                   14008: //#include <tchar.h>
                   14009: //#include <windows.h>
                   14010: //#include <iostream>
                   14011: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   14012: 
                   14013: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14014: 
                   14015: BOOL IsWow64()
                   14016: {
                   14017:        BOOL bIsWow64 = FALSE;
                   14018: 
                   14019:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   14020:        //  (HANDLE, PBOOL);
                   14021: 
                   14022:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14023: 
                   14024:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   14025:        const char funcName[] = "IsWow64Process";
                   14026:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   14027:                GetProcAddress(module, funcName);
                   14028: 
                   14029:        if (NULL != fnIsWow64Process)
                   14030:        {
                   14031:                if (!fnIsWow64Process(GetCurrentProcess(),
                   14032:                        &bIsWow64))
                   14033:                        //throw std::exception("Unknown error");
                   14034:                        printf("Unknown error\n");
                   14035:        }
                   14036:        return bIsWow64 != FALSE;
                   14037: }
                   14038: #endif
1.177     brouard  14039: 
1.191     brouard  14040: void syscompilerinfo(int logged)
1.292     brouard  14041: {
                   14042: #include <stdint.h>
                   14043: 
                   14044:   /* #include "syscompilerinfo.h"*/
1.185     brouard  14045:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   14046:    /* /GS /W3 /Gy
                   14047:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   14048:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   14049:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  14050:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   14051:    */ 
                   14052:    /* 64 bits */
1.185     brouard  14053:    /*
                   14054:      /GS /W3 /Gy
                   14055:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   14056:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   14057:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   14058:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   14059:    /* Optimization are useless and O3 is slower than O2 */
                   14060:    /*
                   14061:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   14062:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   14063:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   14064:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   14065:    */
1.186     brouard  14066:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  14067:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   14068:       /PDB:"visual studio
                   14069:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   14070:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   14071:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   14072:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   14073:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   14074:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   14075:       uiAccess='false'"
                   14076:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   14077:       /NOLOGO /TLBID:1
                   14078:    */
1.292     brouard  14079: 
                   14080: 
1.177     brouard  14081: #if defined __INTEL_COMPILER
1.178     brouard  14082: #if defined(__GNUC__)
                   14083:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   14084: #endif
1.177     brouard  14085: #elif defined(__GNUC__) 
1.179     brouard  14086: #ifndef  __APPLE__
1.174     brouard  14087: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  14088: #endif
1.177     brouard  14089:    struct utsname sysInfo;
1.178     brouard  14090:    int cross = CROSS;
                   14091:    if (cross){
                   14092:           printf("Cross-");
1.191     brouard  14093:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  14094:    }
1.174     brouard  14095: #endif
                   14096: 
1.191     brouard  14097:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  14098: #if defined(__clang__)
1.191     brouard  14099:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  14100: #endif
                   14101: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  14102:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  14103: #endif
                   14104: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  14105:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  14106: #endif
                   14107: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  14108:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  14109: #endif
                   14110: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  14111:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  14112: #endif
                   14113: #if defined(_MSC_VER)
1.191     brouard  14114:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  14115: #endif
                   14116: #if defined(__PGI)
1.191     brouard  14117:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  14118: #endif
                   14119: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  14120:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  14121: #endif
1.191     brouard  14122:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  14123:    
1.167     brouard  14124: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   14125: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   14126:     // Windows (x64 and x86)
1.191     brouard  14127:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  14128: #elif __unix__ // all unices, not all compilers
                   14129:     // Unix
1.191     brouard  14130:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  14131: #elif __linux__
                   14132:     // linux
1.191     brouard  14133:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  14134: #elif __APPLE__
1.174     brouard  14135:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  14136:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  14137: #endif
                   14138: 
                   14139: /*  __MINGW32__          */
                   14140: /*  __CYGWIN__  */
                   14141: /* __MINGW64__  */
                   14142: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   14143: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   14144: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   14145: /* _WIN64  // Defined for applications for Win64. */
                   14146: /* _M_X64 // Defined for compilations that target x64 processors. */
                   14147: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  14148: 
1.167     brouard  14149: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  14150:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  14151: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  14152:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  14153: #else
1.191     brouard  14154:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  14155: #endif
                   14156: 
1.169     brouard  14157: #if defined(__GNUC__)
                   14158: # if defined(__GNUC_PATCHLEVEL__)
                   14159: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14160:                             + __GNUC_MINOR__ * 100 \
                   14161:                             + __GNUC_PATCHLEVEL__)
                   14162: # else
                   14163: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14164:                             + __GNUC_MINOR__ * 100)
                   14165: # endif
1.174     brouard  14166:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  14167:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  14168: 
                   14169:    if (uname(&sysInfo) != -1) {
                   14170:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  14171:         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  14172:    }
                   14173:    else
                   14174:       perror("uname() error");
1.179     brouard  14175:    //#ifndef __INTEL_COMPILER 
                   14176: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  14177:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  14178:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  14179: #endif
1.169     brouard  14180: #endif
1.172     brouard  14181: 
1.286     brouard  14182:    //   void main ()
1.172     brouard  14183:    //   {
1.169     brouard  14184: #if defined(_MSC_VER)
1.174     brouard  14185:    if (IsWow64()){
1.191     brouard  14186:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   14187:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  14188:    }
                   14189:    else{
1.191     brouard  14190:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   14191:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  14192:    }
1.172     brouard  14193:    //     printf("\nPress Enter to continue...");
                   14194:    //     getchar();
                   14195:    //   }
                   14196: 
1.169     brouard  14197: #endif
                   14198:    
1.167     brouard  14199: 
1.219     brouard  14200: }
1.136     brouard  14201: 
1.219     brouard  14202: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  14203:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  14204:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  14205:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  14206:   /* double ftolpl = 1.e-10; */
1.180     brouard  14207:   double age, agebase, agelim;
1.203     brouard  14208:   double tot;
1.180     brouard  14209: 
1.202     brouard  14210:   strcpy(filerespl,"PL_");
                   14211:   strcat(filerespl,fileresu);
                   14212:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  14213:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   14214:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  14215:   }
1.288     brouard  14216:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   14217:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  14218:   pstamp(ficrespl);
1.288     brouard  14219:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  14220:   fprintf(ficrespl,"#Age ");
                   14221:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   14222:   fprintf(ficrespl,"\n");
1.180     brouard  14223:   
1.219     brouard  14224:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  14225: 
1.219     brouard  14226:   agebase=ageminpar;
                   14227:   agelim=agemaxpar;
1.180     brouard  14228: 
1.227     brouard  14229:   /* i1=pow(2,ncoveff); */
1.234     brouard  14230:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  14231:   if (cptcovn < 1){i1=1;}
1.180     brouard  14232: 
1.337     brouard  14233:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  14234:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14235:       k=TKresult[nres];
1.338     brouard  14236:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14237:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   14238:       /*       continue; */
1.235     brouard  14239: 
1.238     brouard  14240:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14241:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   14242:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   14243:       /* k=k+1; */
                   14244:       /* to clean */
1.332     brouard  14245:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  14246:       fprintf(ficrespl,"#******");
                   14247:       printf("#******");
                   14248:       fprintf(ficlog,"#******");
1.337     brouard  14249:       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  14250:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  14251:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14252:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14253:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14254:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14255:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14256:       }
                   14257:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14258:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14259:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14260:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14261:       /* } */
1.238     brouard  14262:       fprintf(ficrespl,"******\n");
                   14263:       printf("******\n");
                   14264:       fprintf(ficlog,"******\n");
                   14265:       if(invalidvarcomb[k]){
                   14266:        printf("\nCombination (%d) ignored because no case \n",k); 
                   14267:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   14268:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   14269:        continue;
                   14270:       }
1.219     brouard  14271: 
1.238     brouard  14272:       fprintf(ficrespl,"#Age ");
1.337     brouard  14273:       /* for(j=1;j<=cptcoveff;j++) { */
                   14274:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14275:       /* } */
                   14276:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   14277:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14278:       }
                   14279:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   14280:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  14281:     
1.238     brouard  14282:       for (age=agebase; age<=agelim; age++){
                   14283:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  14284:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   14285:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  14286:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  14287:        /* for(j=1;j<=cptcoveff;j++) */
                   14288:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14289:        for(j=1;j<=cptcovs;j++)
                   14290:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14291:        tot=0.;
                   14292:        for(i=1; i<=nlstate;i++){
                   14293:          tot +=  prlim[i][i];
                   14294:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   14295:        }
                   14296:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   14297:       } /* Age */
                   14298:       /* was end of cptcod */
1.337     brouard  14299:     } /* nres */
                   14300:   /* } /\* for each combination *\/ */
1.219     brouard  14301:   return 0;
1.180     brouard  14302: }
                   14303: 
1.218     brouard  14304: 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  14305:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  14306:        
                   14307:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   14308:    * at any age between ageminpar and agemaxpar
                   14309:         */
1.235     brouard  14310:   int i, j, k, i1, nres=0 ;
1.217     brouard  14311:   /* double ftolpl = 1.e-10; */
                   14312:   double age, agebase, agelim;
                   14313:   double tot;
1.218     brouard  14314:   /* double ***mobaverage; */
                   14315:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  14316: 
                   14317:   strcpy(fileresplb,"PLB_");
                   14318:   strcat(fileresplb,fileresu);
                   14319:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  14320:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   14321:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  14322:   }
1.288     brouard  14323:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   14324:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  14325:   pstamp(ficresplb);
1.288     brouard  14326:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  14327:   fprintf(ficresplb,"#Age ");
                   14328:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   14329:   fprintf(ficresplb,"\n");
                   14330:   
1.218     brouard  14331:   
                   14332:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   14333:   
                   14334:   agebase=ageminpar;
                   14335:   agelim=agemaxpar;
                   14336:   
                   14337:   
1.227     brouard  14338:   i1=pow(2,cptcoveff);
1.218     brouard  14339:   if (cptcovn < 1){i1=1;}
1.227     brouard  14340:   
1.238     brouard  14341:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  14342:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14343:       k=TKresult[nres];
                   14344:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   14345:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   14346:      /*        continue; */
                   14347:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  14348:       fprintf(ficresplb,"#******");
                   14349:       printf("#******");
                   14350:       fprintf(ficlog,"#******");
1.338     brouard  14351:       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) */
                   14352:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14353:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14354:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14355:       }
1.338     brouard  14356:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   14357:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14358:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14359:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14360:       /* } */
                   14361:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14362:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14363:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14364:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14365:       /* } */
1.238     brouard  14366:       fprintf(ficresplb,"******\n");
                   14367:       printf("******\n");
                   14368:       fprintf(ficlog,"******\n");
                   14369:       if(invalidvarcomb[k]){
                   14370:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   14371:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   14372:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   14373:        continue;
                   14374:       }
1.218     brouard  14375:     
1.238     brouard  14376:       fprintf(ficresplb,"#Age ");
1.338     brouard  14377:       for(j=1;j<=cptcovs;j++) {
                   14378:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14379:       }
                   14380:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   14381:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  14382:     
                   14383:     
1.238     brouard  14384:       for (age=agebase; age<=agelim; age++){
                   14385:        /* for (age=agebase; age<=agebase; age++){ */
                   14386:        if(mobilavproj > 0){
                   14387:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   14388:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14389:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  14390:        }else if (mobilavproj == 0){
                   14391:          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);
                   14392:          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);
                   14393:          exit(1);
                   14394:        }else{
                   14395:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14396:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  14397:          /* printf("TOTOT\n"); */
                   14398:           /* exit(1); */
1.238     brouard  14399:        }
                   14400:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  14401:        for(j=1;j<=cptcovs;j++)
                   14402:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14403:        tot=0.;
                   14404:        for(i=1; i<=nlstate;i++){
                   14405:          tot +=  bprlim[i][i];
                   14406:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   14407:        }
                   14408:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   14409:       } /* Age */
                   14410:       /* was end of cptcod */
1.255     brouard  14411:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  14412:     /* } /\* end of any combination *\/ */
1.238     brouard  14413:   } /* end of nres */  
1.218     brouard  14414:   /* hBijx(p, bage, fage); */
                   14415:   /* fclose(ficrespijb); */
                   14416:   
                   14417:   return 0;
1.217     brouard  14418: }
1.218     brouard  14419:  
1.180     brouard  14420: int hPijx(double *p, int bage, int fage){
                   14421:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  14422:   /* to be optimized with precov */
1.180     brouard  14423:   int stepsize;
                   14424:   int agelim;
                   14425:   int hstepm;
                   14426:   int nhstepm;
1.359     brouard  14427:   int h, i, i1, j, k, nres=0;
1.180     brouard  14428: 
                   14429:   double agedeb;
                   14430:   double ***p3mat;
                   14431: 
1.337     brouard  14432:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   14433:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   14434:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14435:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14436:   }
                   14437:   printf("Computing pij: result on file '%s' \n", filerespij);
                   14438:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   14439:   
                   14440:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14441:   /*if (stepm<=24) stepsize=2;*/
                   14442:   
                   14443:   agelim=AGESUP;
                   14444:   hstepm=stepsize*YEARM; /* Every year of age */
                   14445:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   14446:   
                   14447:   /* hstepm=1;   aff par mois*/
                   14448:   pstamp(ficrespij);
                   14449:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   14450:   i1= pow(2,cptcoveff);
                   14451:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14452:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14453:   /*   k=k+1;  */
                   14454:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14455:     k=TKresult[nres];
1.338     brouard  14456:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14457:     /* for(k=1; k<=i1;k++){ */
                   14458:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   14459:     /*         continue; */
                   14460:     fprintf(ficrespij,"\n#****** ");
                   14461:     for(j=1;j<=cptcovs;j++){
                   14462:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14463:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14464:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14465:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14466:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14467:     }
                   14468:     fprintf(ficrespij,"******\n");
                   14469:     
                   14470:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   14471:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   14472:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   14473:       
                   14474:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14475:       
                   14476:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14477:       oldm=oldms;savm=savms;
                   14478:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   14479:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   14480:       for(i=1; i<=nlstate;i++)
                   14481:        for(j=1; j<=nlstate+ndeath;j++)
                   14482:          fprintf(ficrespij," %1d-%1d",i,j);
                   14483:       fprintf(ficrespij,"\n");
                   14484:       for (h=0; h<=nhstepm; h++){
                   14485:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14486:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  14487:        for(i=1; i<=nlstate;i++)
                   14488:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14489:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  14490:        fprintf(ficrespij,"\n");
                   14491:       }
1.337     brouard  14492:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14493:       fprintf(ficrespij,"\n");
1.180     brouard  14494:     }
1.337     brouard  14495:   }
                   14496:   /*}*/
                   14497:   return 0;
1.180     brouard  14498: }
1.218     brouard  14499:  
                   14500:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  14501:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  14502:     /* To be optimized with precov */
1.217     brouard  14503:   int stepsize;
1.218     brouard  14504:   /* int agelim; */
                   14505:        int ageminl;
1.217     brouard  14506:   int hstepm;
                   14507:   int nhstepm;
1.238     brouard  14508:   int h, i, i1, j, k, nres;
1.218     brouard  14509:        
1.217     brouard  14510:   double agedeb;
                   14511:   double ***p3mat;
1.218     brouard  14512:        
                   14513:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   14514:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   14515:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14516:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14517:   }
                   14518:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   14519:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   14520:   
                   14521:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14522:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  14523:   
1.218     brouard  14524:   /* agelim=AGESUP; */
1.289     brouard  14525:   ageminl=AGEINF; /* was 30 */
1.218     brouard  14526:   hstepm=stepsize*YEARM; /* Every year of age */
                   14527:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   14528:   
                   14529:   /* hstepm=1;   aff par mois*/
                   14530:   pstamp(ficrespijb);
1.255     brouard  14531:   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  14532:   i1= pow(2,cptcoveff);
1.218     brouard  14533:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14534:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14535:   /*   k=k+1;  */
1.238     brouard  14536:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14537:     k=TKresult[nres];
1.338     brouard  14538:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14539:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14540:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   14541:     /*         continue; */
                   14542:     fprintf(ficrespijb,"\n#****** ");
                   14543:     for(j=1;j<=cptcovs;j++){
1.338     brouard  14544:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  14545:       /* for(j=1;j<=cptcoveff;j++) */
                   14546:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14547:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14548:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14549:     }
                   14550:     fprintf(ficrespijb,"******\n");
                   14551:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   14552:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   14553:       continue;
                   14554:     }
                   14555:     
                   14556:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   14557:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   14558:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   14559:       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 */
                   14560:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   14561:       
                   14562:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14563:       
                   14564:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   14565:       /* and memory limitations if stepm is small */
                   14566:       
                   14567:       /* oldm=oldms;savm=savms; */
                   14568:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   14569:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   14570:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   14571:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   14572:       for(i=1; i<=nlstate;i++)
                   14573:        for(j=1; j<=nlstate+ndeath;j++)
                   14574:          fprintf(ficrespijb," %1d-%1d",i,j);
                   14575:       fprintf(ficrespijb,"\n");
                   14576:       for (h=0; h<=nhstepm; h++){
                   14577:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14578:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   14579:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  14580:        for(i=1; i<=nlstate;i++)
                   14581:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14582:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  14583:        fprintf(ficrespijb,"\n");
1.337     brouard  14584:       }
                   14585:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14586:       fprintf(ficrespijb,"\n");
                   14587:     } /* end age deb */
                   14588:     /* } /\* end combination *\/ */
1.238     brouard  14589:   } /* end nres */
1.218     brouard  14590:   return 0;
                   14591:  } /*  hBijx */
1.217     brouard  14592: 
1.180     brouard  14593: 
1.136     brouard  14594: /***********************************************/
                   14595: /**************** Main Program *****************/
                   14596: /***********************************************/
                   14597: 
                   14598: int main(int argc, char *argv[])
                   14599: {
                   14600: #ifdef GSL
                   14601:   const gsl_multimin_fminimizer_type *T;
                   14602:   size_t iteri = 0, it;
                   14603:   int rval = GSL_CONTINUE;
                   14604:   int status = GSL_SUCCESS;
                   14605:   double ssval;
                   14606: #endif
                   14607:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  14608:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   14609:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  14610:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  14611:   int jj, ll, li, lj, lk;
1.136     brouard  14612:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  14613:   int num_filled;
1.136     brouard  14614:   int itimes;
                   14615:   int NDIM=2;
                   14616:   int vpopbased=0;
1.235     brouard  14617:   int nres=0;
1.258     brouard  14618:   int endishere=0;
1.277     brouard  14619:   int noffset=0;
1.274     brouard  14620:   int ncurrv=0; /* Temporary variable */
                   14621:   
1.164     brouard  14622:   char ca[32], cb[32];
1.136     brouard  14623:   /*  FILE *fichtm; *//* Html File */
                   14624:   /* FILE *ficgp;*/ /*Gnuplot File */
                   14625:   struct stat info;
1.191     brouard  14626:   double agedeb=0.;
1.194     brouard  14627: 
                   14628:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  14629:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  14630: 
1.361   ! brouard  14631:   double stdpercent; /* for computing the std error of percent e.i: e.i/e.. */
1.165     brouard  14632:   double fret;
1.191     brouard  14633:   double dum=0.; /* Dummy variable */
1.359     brouard  14634:   /* double*** p3mat;*/
1.218     brouard  14635:   /* double ***mobaverage; */
1.319     brouard  14636:   double wald;
1.164     brouard  14637: 
1.351     brouard  14638:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  14639:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   14640: 
1.234     brouard  14641:   char  modeltemp[MAXLINE];
1.332     brouard  14642:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  14643:   
1.136     brouard  14644:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  14645:   char *tok, *val; /* pathtot */
1.334     brouard  14646:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.359     brouard  14647:   int c, h; /* c2; */
1.191     brouard  14648:   int jl=0;
                   14649:   int i1, j1, jk, stepsize=0;
1.194     brouard  14650:   int count=0;
                   14651: 
1.164     brouard  14652:   int *tab; 
1.136     brouard  14653:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  14654:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   14655:   /* double anprojf, mprojf, jprojf; */
                   14656:   /* double jintmean,mintmean,aintmean;   */
                   14657:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14658:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14659:   double yrfproj= 10.0; /* Number of years of forward projections */
                   14660:   double yrbproj= 10.0; /* Number of years of backward projections */
                   14661:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  14662:   int mobilav=0,popforecast=0;
1.191     brouard  14663:   int hstepm=0, nhstepm=0;
1.136     brouard  14664:   int agemortsup;
                   14665:   float  sumlpop=0.;
                   14666:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   14667:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   14668: 
1.191     brouard  14669:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  14670:   double ftolpl=FTOL;
                   14671:   double **prlim;
1.217     brouard  14672:   double **bprlim;
1.317     brouard  14673:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   14674:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  14675:   double ***paramstart; /* Matrix of starting parameter values */
                   14676:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  14677:   double **matcov; /* Matrix of covariance */
1.203     brouard  14678:   double **hess; /* Hessian matrix */
1.136     brouard  14679:   double ***delti3; /* Scale */
                   14680:   double *delti; /* Scale */
                   14681:   double ***eij, ***vareij;
1.359     brouard  14682:   //double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  14683: 
1.136     brouard  14684:   double *epj, vepp;
1.164     brouard  14685: 
1.273     brouard  14686:   double dateprev1, dateprev2;
1.296     brouard  14687:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   14688:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   14689: 
1.217     brouard  14690: 
1.136     brouard  14691:   double **ximort;
1.145     brouard  14692:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  14693:   int *dcwave;
                   14694: 
1.164     brouard  14695:   char z[1]="c";
1.136     brouard  14696: 
                   14697:   /*char  *strt;*/
                   14698:   char strtend[80];
1.126     brouard  14699: 
1.164     brouard  14700: 
1.126     brouard  14701: /*   setlocale (LC_ALL, ""); */
                   14702: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   14703: /*   textdomain (PACKAGE); */
                   14704: /*   setlocale (LC_CTYPE, ""); */
                   14705: /*   setlocale (LC_MESSAGES, ""); */
                   14706: 
                   14707:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  14708:   rstart_time = time(NULL);  
                   14709:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   14710:   start_time = *localtime(&rstart_time);
1.126     brouard  14711:   curr_time=start_time;
1.157     brouard  14712:   /*tml = *localtime(&start_time.tm_sec);*/
                   14713:   /* strcpy(strstart,asctime(&tml)); */
                   14714:   strcpy(strstart,asctime(&start_time));
1.126     brouard  14715: 
                   14716: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  14717: /*  tp.tm_sec = tp.tm_sec +86400; */
                   14718: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  14719: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   14720: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   14721: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  14722: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  14723: /*   strt=asctime(&tmg); */
                   14724: /*   printf("Time(after) =%s",strstart);  */
                   14725: /*  (void) time (&time_value);
                   14726: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   14727: *  tm = *localtime(&time_value);
                   14728: *  strstart=asctime(&tm);
                   14729: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   14730: */
                   14731: 
                   14732:   nberr=0; /* Number of errors and warnings */
                   14733:   nbwarn=0;
1.184     brouard  14734: #ifdef WIN32
                   14735:   _getcwd(pathcd, size);
                   14736: #else
1.126     brouard  14737:   getcwd(pathcd, size);
1.184     brouard  14738: #endif
1.191     brouard  14739:   syscompilerinfo(0);
1.359     brouard  14740:   printf("\nIMaCh prax version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  14741:   if(argc <=1){
                   14742:     printf("\nEnter the parameter file name: ");
1.205     brouard  14743:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   14744:       printf("ERROR Empty parameter file name\n");
                   14745:       goto end;
                   14746:     }
1.126     brouard  14747:     i=strlen(pathr);
                   14748:     if(pathr[i-1]=='\n')
                   14749:       pathr[i-1]='\0';
1.156     brouard  14750:     i=strlen(pathr);
1.205     brouard  14751:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  14752:       pathr[i-1]='\0';
1.205     brouard  14753:     }
                   14754:     i=strlen(pathr);
                   14755:     if( i==0 ){
                   14756:       printf("ERROR Empty parameter file name\n");
                   14757:       goto end;
                   14758:     }
                   14759:     for (tok = pathr; tok != NULL; ){
1.126     brouard  14760:       printf("Pathr |%s|\n",pathr);
                   14761:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   14762:       printf("val= |%s| pathr=%s\n",val,pathr);
                   14763:       strcpy (pathtot, val);
                   14764:       if(pathr[0] == '\0') break; /* Dirty */
                   14765:     }
                   14766:   }
1.281     brouard  14767:   else if (argc<=2){
                   14768:     strcpy(pathtot,argv[1]);
                   14769:   }
1.126     brouard  14770:   else{
                   14771:     strcpy(pathtot,argv[1]);
1.281     brouard  14772:     strcpy(z,argv[2]);
                   14773:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  14774:   }
                   14775:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   14776:   /*cygwin_split_path(pathtot,path,optionfile);
                   14777:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   14778:   /* cutv(path,optionfile,pathtot,'\\');*/
                   14779: 
                   14780:   /* Split argv[0], imach program to get pathimach */
                   14781:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   14782:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14783:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14784:  /*   strcpy(pathimach,argv[0]); */
                   14785:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   14786:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   14787:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  14788: #ifdef WIN32
                   14789:   _chdir(path); /* Can be a relative path */
                   14790:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   14791: #else
1.126     brouard  14792:   chdir(path); /* Can be a relative path */
1.184     brouard  14793:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   14794: #endif
                   14795:   printf("Current directory %s!\n",pathcd);
1.126     brouard  14796:   strcpy(command,"mkdir ");
                   14797:   strcat(command,optionfilefiname);
                   14798:   if((outcmd=system(command)) != 0){
1.169     brouard  14799:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  14800:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   14801:     /* fclose(ficlog); */
                   14802: /*     exit(1); */
                   14803:   }
                   14804: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   14805: /*     perror("mkdir"); */
                   14806: /*   } */
                   14807: 
                   14808:   /*-------- arguments in the command line --------*/
                   14809: 
1.186     brouard  14810:   /* Main Log file */
1.126     brouard  14811:   strcat(filelog, optionfilefiname);
                   14812:   strcat(filelog,".log");    /* */
                   14813:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   14814:     printf("Problem with logfile %s\n",filelog);
                   14815:     goto end;
                   14816:   }
                   14817:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  14818:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  14819:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   14820:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   14821:  path=%s \n\
                   14822:  optionfile=%s\n\
                   14823:  optionfilext=%s\n\
1.156     brouard  14824:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  14825: 
1.197     brouard  14826:   syscompilerinfo(1);
1.167     brouard  14827: 
1.126     brouard  14828:   printf("Local time (at start):%s",strstart);
                   14829:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   14830:   fflush(ficlog);
                   14831: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  14832: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  14833: 
                   14834:   /* */
                   14835:   strcpy(fileres,"r");
                   14836:   strcat(fileres, optionfilefiname);
1.201     brouard  14837:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  14838:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  14839:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  14840: 
1.186     brouard  14841:   /* Main ---------arguments file --------*/
1.126     brouard  14842: 
                   14843:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  14844:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   14845:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  14846:     fflush(ficlog);
1.149     brouard  14847:     /* goto end; */
                   14848:     exit(70); 
1.126     brouard  14849:   }
                   14850: 
                   14851:   strcpy(filereso,"o");
1.201     brouard  14852:   strcat(filereso,fileresu);
1.126     brouard  14853:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   14854:     printf("Problem with Output resultfile: %s\n", filereso);
                   14855:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   14856:     fflush(ficlog);
                   14857:     goto end;
                   14858:   }
1.278     brouard  14859:       /*-------- Rewriting parameter file ----------*/
                   14860:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   14861:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   14862:   strcat(rfileres,".");    /* */
                   14863:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   14864:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   14865:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   14866:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   14867:     fflush(ficlog);
                   14868:     goto end;
                   14869:   }
                   14870:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  14871: 
1.278     brouard  14872:                                      
1.126     brouard  14873:   /* Reads comments: lines beginning with '#' */
                   14874:   numlinepar=0;
1.277     brouard  14875:   /* Is it a BOM UTF-8 Windows file? */
                   14876:   /* First parameter line */
1.197     brouard  14877:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  14878:     noffset=0;
                   14879:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   14880:     {
                   14881:       noffset=noffset+3;
                   14882:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   14883:     }
1.302     brouard  14884: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   14885:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  14886:     {
                   14887:       noffset=noffset+2;
                   14888:       printf("# File is an UTF16BE BOM file\n");
                   14889:     }
                   14890:     else if( line[0] == 0 && line[1] == 0)
                   14891:     {
                   14892:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   14893:        noffset=noffset+4;
                   14894:        printf("# File is an UTF16BE BOM file\n");
                   14895:       }
                   14896:     } else{
                   14897:       ;/*printf(" Not a BOM file\n");*/
                   14898:     }
                   14899:   
1.197     brouard  14900:     /* If line starts with a # it is a comment */
1.277     brouard  14901:     if (line[noffset] == '#') {
1.197     brouard  14902:       numlinepar++;
                   14903:       fputs(line,stdout);
                   14904:       fputs(line,ficparo);
1.278     brouard  14905:       fputs(line,ficres);
1.197     brouard  14906:       fputs(line,ficlog);
                   14907:       continue;
                   14908:     }else
                   14909:       break;
                   14910:   }
                   14911:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   14912:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   14913:     if (num_filled != 5) {
                   14914:       printf("Should be 5 parameters\n");
1.283     brouard  14915:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  14916:     }
1.126     brouard  14917:     numlinepar++;
1.197     brouard  14918:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  14919:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14920:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14921:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  14922:   }
                   14923:   /* Second parameter line */
                   14924:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  14925:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   14926:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  14927:     if (line[0] == '#') {
                   14928:       numlinepar++;
1.283     brouard  14929:       printf("%s",line);
                   14930:       fprintf(ficres,"%s",line);
                   14931:       fprintf(ficparo,"%s",line);
                   14932:       fprintf(ficlog,"%s",line);
1.197     brouard  14933:       continue;
                   14934:     }else
                   14935:       break;
                   14936:   }
1.223     brouard  14937:   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", \
                   14938:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   14939:     if (num_filled != 11) {
                   14940:       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  14941:       printf("but line=%s\n",line);
1.283     brouard  14942:       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");
                   14943:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  14944:     }
1.286     brouard  14945:     if( lastpass > maxwav){
                   14946:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14947:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14948:       fflush(ficlog);
                   14949:       goto end;
                   14950:     }
                   14951:       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  14952:     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  14953:     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  14954:     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  14955:   }
1.203     brouard  14956:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  14957:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  14958:   /* Third parameter line */
                   14959:   while(fgets(line, MAXLINE, ficpar)) {
                   14960:     /* If line starts with a # it is a comment */
                   14961:     if (line[0] == '#') {
                   14962:       numlinepar++;
1.283     brouard  14963:       printf("%s",line);
                   14964:       fprintf(ficres,"%s",line);
                   14965:       fprintf(ficparo,"%s",line);
                   14966:       fprintf(ficlog,"%s",line);
1.197     brouard  14967:       continue;
                   14968:     }else
                   14969:       break;
                   14970:   }
1.351     brouard  14971:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   14972:     if (num_filled != 1){
                   14973:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14974:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14975:       model[0]='\0';
                   14976:       goto end;
                   14977:     }else{
                   14978:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   14979:       strcpy(line, linetmp);
                   14980:     }
                   14981:   }
                   14982:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  14983:     if (num_filled != 1){
1.302     brouard  14984:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14985:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  14986:       model[0]='\0';
                   14987:       goto end;
                   14988:     }
                   14989:     else{
                   14990:       if (model[0]=='+'){
                   14991:        for(i=1; i<=strlen(model);i++)
                   14992:          modeltemp[i-1]=model[i];
1.201     brouard  14993:        strcpy(model,modeltemp); 
1.197     brouard  14994:       }
                   14995:     }
1.338     brouard  14996:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  14997:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  14998:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   14999:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   15000:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  15001:   }
                   15002:   /* 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); */
                   15003:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   15004:   /* 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  15005:   /* 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); */
                   15006:   /* 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  15007:   fflush(ficlog);
1.190     brouard  15008:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   15009:   if(model[0]=='#'){
1.279     brouard  15010:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   15011:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   15012:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  15013:     if(mle != -1){
1.279     brouard  15014:       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  15015:       exit(1);
                   15016:     }
                   15017:   }
1.126     brouard  15018:   while((c=getc(ficpar))=='#' && c!= EOF){
                   15019:     ungetc(c,ficpar);
                   15020:     fgets(line, MAXLINE, ficpar);
                   15021:     numlinepar++;
1.195     brouard  15022:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   15023:       z[0]=line[1];
1.342     brouard  15024:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  15025:       debugILK=1;printf("DebugILK\n");
1.195     brouard  15026:     }
                   15027:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  15028:     fputs(line, stdout);
                   15029:     //puts(line);
1.126     brouard  15030:     fputs(line,ficparo);
                   15031:     fputs(line,ficlog);
                   15032:   }
                   15033:   ungetc(c,ficpar);
                   15034: 
                   15035:    
1.290     brouard  15036:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   15037:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   15038:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  15039:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   15040:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  15041:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   15042:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   15043:      v1+v2*age+v2*v3 makes cptcovn = 3
                   15044:   */
                   15045:   if (strlen(model)>1) 
1.187     brouard  15046:     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  15047:   else
1.187     brouard  15048:     ncovmodel=2; /* Constant and age */
1.133     brouard  15049:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   15050:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  15051:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   15052:     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);
                   15053:     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);
                   15054:     fflush(stdout);
                   15055:     fclose (ficlog);
                   15056:     goto end;
                   15057:   }
1.126     brouard  15058:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15059:   delti=delti3[1][1];
                   15060:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   15061:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  15062: /* We could also provide initial parameters values giving by simple logistic regression 
                   15063:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   15064:       /* for(i=1;i<nlstate;i++){ */
                   15065:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15066:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15067:       /* } */
1.126     brouard  15068:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  15069:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   15070:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15071:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15072:     fclose (ficparo);
                   15073:     fclose (ficlog);
                   15074:     goto end;
                   15075:     exit(0);
1.220     brouard  15076:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  15077:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  15078:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   15079:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15080:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15081:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15082:     hess=matrix(1,npar,1,npar);
1.220     brouard  15083:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  15084:     /* Read guessed parameters */
1.126     brouard  15085:     /* Reads comments: lines beginning with '#' */
                   15086:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15087:       ungetc(c,ficpar);
                   15088:       fgets(line, MAXLINE, ficpar);
                   15089:       numlinepar++;
1.141     brouard  15090:       fputs(line,stdout);
1.126     brouard  15091:       fputs(line,ficparo);
                   15092:       fputs(line,ficlog);
                   15093:     }
                   15094:     ungetc(c,ficpar);
                   15095:     
                   15096:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  15097:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  15098:     for(i=1; i <=nlstate; i++){
1.234     brouard  15099:       j=0;
1.126     brouard  15100:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  15101:        if(jj==i) continue;
                   15102:        j++;
1.292     brouard  15103:        while((c=getc(ficpar))=='#' && c!= EOF){
                   15104:          ungetc(c,ficpar);
                   15105:          fgets(line, MAXLINE, ficpar);
                   15106:          numlinepar++;
                   15107:          fputs(line,stdout);
                   15108:          fputs(line,ficparo);
                   15109:          fputs(line,ficlog);
                   15110:        }
                   15111:        ungetc(c,ficpar);
1.234     brouard  15112:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15113:        if ((i1 != i) || (j1 != jj)){
                   15114:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  15115: It might be a problem of design; if ncovcol and the model are correct\n \
                   15116: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  15117:          exit(1);
                   15118:        }
                   15119:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15120:        if(mle==1)
                   15121:          printf("%1d%1d",i,jj);
                   15122:        fprintf(ficlog,"%1d%1d",i,jj);
                   15123:        for(k=1; k<=ncovmodel;k++){
                   15124:          fscanf(ficpar," %lf",&param[i][j][k]);
                   15125:          if(mle==1){
                   15126:            printf(" %lf",param[i][j][k]);
                   15127:            fprintf(ficlog," %lf",param[i][j][k]);
                   15128:          }
                   15129:          else
                   15130:            fprintf(ficlog," %lf",param[i][j][k]);
                   15131:          fprintf(ficparo," %lf",param[i][j][k]);
                   15132:        }
                   15133:        fscanf(ficpar,"\n");
                   15134:        numlinepar++;
                   15135:        if(mle==1)
                   15136:          printf("\n");
                   15137:        fprintf(ficlog,"\n");
                   15138:        fprintf(ficparo,"\n");
1.126     brouard  15139:       }
                   15140:     }  
                   15141:     fflush(ficlog);
1.234     brouard  15142:     
1.251     brouard  15143:     /* Reads parameters values */
1.126     brouard  15144:     p=param[1][1];
1.251     brouard  15145:     pstart=paramstart[1][1];
1.126     brouard  15146:     
                   15147:     /* Reads comments: lines beginning with '#' */
                   15148:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15149:       ungetc(c,ficpar);
                   15150:       fgets(line, MAXLINE, ficpar);
                   15151:       numlinepar++;
1.141     brouard  15152:       fputs(line,stdout);
1.126     brouard  15153:       fputs(line,ficparo);
                   15154:       fputs(line,ficlog);
                   15155:     }
                   15156:     ungetc(c,ficpar);
                   15157: 
                   15158:     for(i=1; i <=nlstate; i++){
                   15159:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  15160:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15161:        if ( (i1-i) * (j1-j) != 0){
                   15162:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   15163:          exit(1);
                   15164:        }
                   15165:        printf("%1d%1d",i,j);
                   15166:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15167:        fprintf(ficlog,"%1d%1d",i1,j1);
                   15168:        for(k=1; k<=ncovmodel;k++){
                   15169:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   15170:          printf(" %le",delti3[i][j][k]);
                   15171:          fprintf(ficparo," %le",delti3[i][j][k]);
                   15172:          fprintf(ficlog," %le",delti3[i][j][k]);
                   15173:        }
                   15174:        fscanf(ficpar,"\n");
                   15175:        numlinepar++;
                   15176:        printf("\n");
                   15177:        fprintf(ficparo,"\n");
                   15178:        fprintf(ficlog,"\n");
1.126     brouard  15179:       }
                   15180:     }
                   15181:     fflush(ficlog);
1.234     brouard  15182:     
1.145     brouard  15183:     /* Reads covariance matrix */
1.126     brouard  15184:     delti=delti3[1][1];
1.220     brouard  15185:                
                   15186:                
1.126     brouard  15187:     /* 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  15188:                
1.126     brouard  15189:     /* Reads comments: lines beginning with '#' */
                   15190:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15191:       ungetc(c,ficpar);
                   15192:       fgets(line, MAXLINE, ficpar);
                   15193:       numlinepar++;
1.141     brouard  15194:       fputs(line,stdout);
1.126     brouard  15195:       fputs(line,ficparo);
                   15196:       fputs(line,ficlog);
                   15197:     }
                   15198:     ungetc(c,ficpar);
1.220     brouard  15199:                
1.126     brouard  15200:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15201:     hess=matrix(1,npar,1,npar);
1.131     brouard  15202:     for(i=1; i <=npar; i++)
                   15203:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  15204:                
1.194     brouard  15205:     /* Scans npar lines */
1.126     brouard  15206:     for(i=1; i <=npar; i++){
1.226     brouard  15207:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  15208:       if(count != 3){
1.226     brouard  15209:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15210: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15211: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15212:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15213: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15214: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15215:        exit(1);
1.220     brouard  15216:       }else{
1.226     brouard  15217:        if(mle==1)
                   15218:          printf("%1d%1d%d",i1,j1,jk);
                   15219:       }
                   15220:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   15221:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  15222:       for(j=1; j <=i; j++){
1.226     brouard  15223:        fscanf(ficpar," %le",&matcov[i][j]);
                   15224:        if(mle==1){
                   15225:          printf(" %.5le",matcov[i][j]);
                   15226:        }
                   15227:        fprintf(ficlog," %.5le",matcov[i][j]);
                   15228:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  15229:       }
                   15230:       fscanf(ficpar,"\n");
                   15231:       numlinepar++;
                   15232:       if(mle==1)
1.220     brouard  15233:                                printf("\n");
1.126     brouard  15234:       fprintf(ficlog,"\n");
                   15235:       fprintf(ficparo,"\n");
                   15236:     }
1.194     brouard  15237:     /* End of read covariance matrix npar lines */
1.126     brouard  15238:     for(i=1; i <=npar; i++)
                   15239:       for(j=i+1;j<=npar;j++)
1.226     brouard  15240:        matcov[i][j]=matcov[j][i];
1.126     brouard  15241:     
                   15242:     if(mle==1)
                   15243:       printf("\n");
                   15244:     fprintf(ficlog,"\n");
                   15245:     
                   15246:     fflush(ficlog);
                   15247:     
                   15248:   }    /* End of mle != -3 */
1.218     brouard  15249:   
1.186     brouard  15250:   /*  Main data
                   15251:    */
1.290     brouard  15252:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   15253:   /* num=lvector(1,n); */
                   15254:   /* moisnais=vector(1,n); */
                   15255:   /* annais=vector(1,n); */
                   15256:   /* moisdc=vector(1,n); */
                   15257:   /* andc=vector(1,n); */
                   15258:   /* weight=vector(1,n); */
                   15259:   /* agedc=vector(1,n); */
                   15260:   /* cod=ivector(1,n); */
                   15261:   /* for(i=1;i<=n;i++){ */
                   15262:   num=lvector(firstobs,lastobs);
                   15263:   moisnais=vector(firstobs,lastobs);
                   15264:   annais=vector(firstobs,lastobs);
                   15265:   moisdc=vector(firstobs,lastobs);
                   15266:   andc=vector(firstobs,lastobs);
                   15267:   weight=vector(firstobs,lastobs);
                   15268:   agedc=vector(firstobs,lastobs);
                   15269:   cod=ivector(firstobs,lastobs);
                   15270:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  15271:     num[i]=0;
                   15272:     moisnais[i]=0;
                   15273:     annais[i]=0;
                   15274:     moisdc[i]=0;
                   15275:     andc[i]=0;
                   15276:     agedc[i]=0;
                   15277:     cod[i]=0;
                   15278:     weight[i]=1.0; /* Equal weights, 1 by default */
                   15279:   }
1.290     brouard  15280:   mint=matrix(1,maxwav,firstobs,lastobs);
                   15281:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  15282:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  15283:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  15284:   tab=ivector(1,NCOVMAX);
1.144     brouard  15285:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  15286:   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  15287: 
1.136     brouard  15288:   /* Reads data from file datafile */
                   15289:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   15290:     goto end;
                   15291: 
                   15292:   /* Calculation of the number of parameters from char model */
1.234     brouard  15293:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  15294:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   15295:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   15296:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   15297:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  15298:   */
                   15299:   
                   15300:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   15301:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  15302:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  15303:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  15304:   TvarsD=ivector(1,NCOVMAX); /*  */
                   15305:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   15306:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  15307:   TvarF=ivector(1,NCOVMAX); /*  */
                   15308:   TvarFind=ivector(1,NCOVMAX); /*  */
                   15309:   TvarV=ivector(1,NCOVMAX); /*  */
                   15310:   TvarVind=ivector(1,NCOVMAX); /*  */
                   15311:   TvarA=ivector(1,NCOVMAX); /*  */
                   15312:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15313:   TvarFD=ivector(1,NCOVMAX); /*  */
                   15314:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   15315:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   15316:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   15317:   TvarVD=ivector(1,NCOVMAX); /*  */
                   15318:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   15319:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   15320:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  15321:   TvarVV=ivector(1,NCOVMAX); /*  */
                   15322:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  15323:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   15324:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   15325:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   15326:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15327: 
1.230     brouard  15328:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  15329:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  15330:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   15331:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   15332:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  15333:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15334:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15335: 
1.137     brouard  15336:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   15337:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   15338:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   15339:   */
                   15340:   /* For model-covariate k tells which data-covariate to use but
                   15341:     because this model-covariate is a construction we invent a new column
                   15342:     ncovcol + k1
                   15343:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   15344:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  15345:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   15346:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  15347:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   15348:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  15349:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  15350:   */
1.145     brouard  15351:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   15352:   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  15353:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   15354:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  15355:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  15356:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  15357:                         4 covariates (3 plus signs)
                   15358:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  15359:                           */  
                   15360:   for(i=1;i<NCOVMAX;i++)
                   15361:     Tage[i]=0;
1.230     brouard  15362:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  15363:                                * individual dummy, fixed or varying:
                   15364:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   15365:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  15366:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   15367:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   15368:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   15369:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   15370:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  15371:                                * individual quantitative, fixed or varying:
                   15372:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   15373:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   15374:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  15375: 
                   15376: /* Probably useless zeroes */
                   15377:   for(i=1;i<NCOVMAX;i++){
                   15378:     DummyV[i]=0;
                   15379:     FixedV[i]=0;
                   15380:   }
                   15381: 
                   15382:   for(i=1; i <=ncovcol;i++){
                   15383:     DummyV[i]=0;
                   15384:     FixedV[i]=0;
                   15385:   }
                   15386:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   15387:     DummyV[i]=1;
                   15388:     FixedV[i]=0;
                   15389:   }
                   15390:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   15391:     DummyV[i]=0;
                   15392:     FixedV[i]=1;
                   15393:   }
                   15394:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15395:     DummyV[i]=1;
                   15396:     FixedV[i]=1;
                   15397:   }
                   15398:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15399:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15400:     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]);
                   15401:   }
                   15402: 
                   15403: 
                   15404: 
1.186     brouard  15405: /* Main decodemodel */
                   15406: 
1.187     brouard  15407: 
1.223     brouard  15408:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  15409:     goto end;
                   15410: 
1.137     brouard  15411:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   15412:     nbwarn++;
                   15413:     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); 
                   15414:     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); 
                   15415:   }
1.136     brouard  15416:     /*  if(mle==1){*/
1.137     brouard  15417:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   15418:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  15419:   }
                   15420: 
                   15421:     /*-calculation of age at interview from date of interview and age at death -*/
                   15422:   agev=matrix(1,maxwav,1,imx);
                   15423: 
                   15424:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   15425:     goto end;
                   15426: 
1.126     brouard  15427: 
1.136     brouard  15428:   agegomp=(int)agemin;
1.290     brouard  15429:   free_vector(moisnais,firstobs,lastobs);
                   15430:   free_vector(annais,firstobs,lastobs);
1.126     brouard  15431:   /* free_matrix(mint,1,maxwav,1,n);
                   15432:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  15433:   /* free_vector(moisdc,1,n); */
                   15434:   /* free_vector(andc,1,n); */
1.145     brouard  15435:   /* */
                   15436:   
1.126     brouard  15437:   wav=ivector(1,imx);
1.214     brouard  15438:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15439:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15440:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15441:   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.*/
                   15442:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   15443:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  15444:    
                   15445:   /* Concatenates waves */
1.214     brouard  15446:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   15447:      Death is a valid wave (if date is known).
                   15448:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   15449:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   15450:      and mw[mi+1][i]. dh depends on stepm.
                   15451:   */
                   15452: 
1.126     brouard  15453:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  15454:   /* Concatenates waves */
1.145     brouard  15455:  
1.290     brouard  15456:   free_vector(moisdc,firstobs,lastobs);
                   15457:   free_vector(andc,firstobs,lastobs);
1.215     brouard  15458: 
1.126     brouard  15459:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   15460:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   15461:   ncodemax[1]=1;
1.145     brouard  15462:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  15463:   cptcoveff=0;
1.220     brouard  15464:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  15465:     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  15466:   }
                   15467:   
                   15468:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  15469:   invalidvarcomb=ivector(0, ncovcombmax); 
                   15470:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  15471:     invalidvarcomb[i]=0;
                   15472:   
1.211     brouard  15473:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  15474:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  15475:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  15476:   
1.200     brouard  15477:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  15478:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  15479:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  15480:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   15481:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   15482:    * (currently 0 or 1) in the data.
                   15483:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   15484:    * corresponding modality (h,j).
                   15485:    */
                   15486: 
1.145     brouard  15487:   h=0;
                   15488:   /*if (cptcovn > 0) */
1.126     brouard  15489:   m=pow(2,cptcoveff);
                   15490:  
1.144     brouard  15491:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  15492:           * For k=4 covariates, h goes from 1 to m=2**k
                   15493:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   15494:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  15495:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   15496:           *______________________________   *______________________
                   15497:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   15498:           *     2     2     1     1     1   *     1     0  0  0  1 
                   15499:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   15500:           *     4     2     2     1     1   *     3     0  0  1  1 
                   15501:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   15502:           *     6     2     1     2     1   *     5     0  1  0  1 
                   15503:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   15504:           *     8     2     2     2     1   *     7     0  1  1  1 
                   15505:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   15506:           *    10     2     1     1     2   *     9     1  0  0  1 
                   15507:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   15508:           *    12     2     2     1     2   *    11     1  0  1  1 
                   15509:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   15510:           *    14     2     1     2     2   *    13     1  1  0  1 
                   15511:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   15512:           *    16     2     2     2     2   *    15     1  1  1  1          
                   15513:           */                                     
1.212     brouard  15514:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  15515:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   15516:      * and the value of each covariate?
                   15517:      * V1=1, V2=1, V3=2, V4=1 ?
                   15518:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   15519:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   15520:      * In order to get the real value in the data, we use nbcode
                   15521:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   15522:      * We are keeping this crazy system in order to be able (in the future?) 
                   15523:      * to have more than 2 values (0 or 1) for a covariate.
                   15524:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   15525:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   15526:      *              bbbbbbbb
                   15527:      *              76543210     
                   15528:      *   h-1        00000101 (6-1=5)
1.219     brouard  15529:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  15530:      *           &
                   15531:      *     1        00000001 (1)
1.219     brouard  15532:      *              00000000        = 1 & ((h-1) >> (k-1))
                   15533:      *          +1= 00000001 =1 
1.211     brouard  15534:      *
                   15535:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   15536:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   15537:      *    >>k'            11
                   15538:      *          &   00000001
                   15539:      *            = 00000001
                   15540:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   15541:      * Reverse h=6 and m=16?
                   15542:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   15543:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   15544:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   15545:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   15546:      * V3=decodtabm(14,3,2**4)=2
                   15547:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   15548:      *(h-1) >> (j-1)    0011 =13 >> 2
                   15549:      *          &1 000000001
                   15550:      *           = 000000001
                   15551:      *         +1= 000000010 =2
                   15552:      *                  2211
                   15553:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   15554:      *                  V3=2
1.220     brouard  15555:                 * codtabm and decodtabm are identical
1.211     brouard  15556:      */
                   15557: 
1.145     brouard  15558: 
                   15559:  free_ivector(Ndum,-1,NCOVMAX);
                   15560: 
                   15561: 
1.126     brouard  15562:     
1.186     brouard  15563:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  15564:   strcpy(optionfilegnuplot,optionfilefiname);
                   15565:   if(mle==-3)
1.201     brouard  15566:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  15567:   strcat(optionfilegnuplot,".gp");
                   15568: 
                   15569:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   15570:     printf("Problem with file %s",optionfilegnuplot);
                   15571:   }
                   15572:   else{
1.204     brouard  15573:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  15574:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  15575:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   15576:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  15577:   }
                   15578:   /*  fclose(ficgp);*/
1.186     brouard  15579: 
                   15580: 
                   15581:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  15582: 
                   15583:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   15584:   if(mle==-3)
1.201     brouard  15585:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  15586:   strcat(optionfilehtm,".htm");
                   15587:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  15588:     printf("Problem with %s \n",optionfilehtm);
                   15589:     exit(0);
1.126     brouard  15590:   }
                   15591: 
                   15592:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   15593:   strcat(optionfilehtmcov,"-cov.htm");
                   15594:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   15595:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   15596:   }
                   15597:   else{
                   15598:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   15599: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15600: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  15601:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   15602:   }
                   15603: 
1.335     brouard  15604:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   15605: <title>IMaCh %s</title></head>\n\
                   15606:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   15607: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   15608: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   15609: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   15610: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   15611:   
                   15612:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15613: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  15614: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  15615: 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  15616: \n\
                   15617: <hr  size=\"2\" color=\"#EC5E5E\">\
                   15618:  <ul><li><h4>Parameter files</h4>\n\
                   15619:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   15620:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   15621:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   15622:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   15623:  - Date and time at start: %s</ul>\n",\
1.335     brouard  15624:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  15625:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   15626:          fileres,fileres,\
                   15627:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   15628:   fflush(fichtm);
                   15629: 
                   15630:   strcpy(pathr,path);
                   15631:   strcat(pathr,optionfilefiname);
1.184     brouard  15632: #ifdef WIN32
                   15633:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   15634: #else
1.126     brouard  15635:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  15636: #endif
                   15637:          
1.126     brouard  15638:   
1.220     brouard  15639:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   15640:                 and for any valid combination of covariates
1.126     brouard  15641:      and prints on file fileres'p'. */
1.359     brouard  15642:   freqsummary(fileres, p, pstart, (double)agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  15643:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  15644: 
                   15645:   fprintf(fichtm,"\n");
1.286     brouard  15646:   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  15647:          ftol, stepm);
                   15648:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   15649:   ncurrv=1;
                   15650:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   15651:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   15652:   ncurrv=i;
                   15653:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15654:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  15655:   ncurrv=i;
                   15656:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15657:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  15658:   ncurrv=i;
                   15659:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   15660:   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", \
                   15661:           nlstate, ndeath, maxwav, mle, weightopt);
                   15662: 
                   15663:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   15664: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   15665: 
                   15666:   
1.317     brouard  15667:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  15668: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   15669: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  15670:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  15671:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  15672:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15673:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15674:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15675:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  15676: 
1.126     brouard  15677:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   15678:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   15679:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   15680: 
                   15681:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  15682:   /* For mortality only */
1.126     brouard  15683:   if (mle==-3){
1.136     brouard  15684:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  15685:     for(i=1;i<=NDIM;i++)
                   15686:       for(j=1;j<=NDIM;j++)
                   15687:        ximort[i][j]=0.;
1.186     brouard  15688:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  15689:     cens=ivector(firstobs,lastobs);
                   15690:     ageexmed=vector(firstobs,lastobs);
                   15691:     agecens=vector(firstobs,lastobs);
                   15692:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  15693:                
1.126     brouard  15694:     for (i=1; i<=imx; i++){
                   15695:       dcwave[i]=-1;
                   15696:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  15697:        if (s[m][i]>nlstate) {
                   15698:          dcwave[i]=m;
                   15699:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   15700:          break;
                   15701:        }
1.126     brouard  15702:     }
1.226     brouard  15703:     
1.126     brouard  15704:     for (i=1; i<=imx; i++) {
                   15705:       if (wav[i]>0){
1.226     brouard  15706:        ageexmed[i]=agev[mw[1][i]][i];
                   15707:        j=wav[i];
                   15708:        agecens[i]=1.; 
                   15709:        
                   15710:        if (ageexmed[i]> 1 && wav[i] > 0){
                   15711:          agecens[i]=agev[mw[j][i]][i];
                   15712:          cens[i]= 1;
                   15713:        }else if (ageexmed[i]< 1) 
                   15714:          cens[i]= -1;
                   15715:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   15716:          cens[i]=0 ;
1.126     brouard  15717:       }
                   15718:       else cens[i]=-1;
                   15719:     }
                   15720:     
                   15721:     for (i=1;i<=NDIM;i++) {
                   15722:       for (j=1;j<=NDIM;j++)
1.226     brouard  15723:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  15724:     }
                   15725:     
1.302     brouard  15726:     p[1]=0.0268; p[NDIM]=0.083;
                   15727:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  15728:     
                   15729:     
1.136     brouard  15730: #ifdef GSL
                   15731:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  15732: #else
1.359     brouard  15733:     printf("Powell-mort\n");  fprintf(ficlog,"Powell-mort\n");
1.136     brouard  15734: #endif
1.201     brouard  15735:     strcpy(filerespow,"POW-MORT_"); 
                   15736:     strcat(filerespow,fileresu);
1.126     brouard  15737:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   15738:       printf("Problem with resultfile: %s\n", filerespow);
                   15739:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   15740:     }
1.136     brouard  15741: #ifdef GSL
                   15742:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  15743: #else
1.126     brouard  15744:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  15745: #endif
1.126     brouard  15746:     /*  for (i=1;i<=nlstate;i++)
                   15747:        for(j=1;j<=nlstate+ndeath;j++)
                   15748:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   15749:     */
                   15750:     fprintf(ficrespow,"\n");
1.136     brouard  15751: #ifdef GSL
                   15752:     /* gsl starts here */ 
                   15753:     T = gsl_multimin_fminimizer_nmsimplex;
                   15754:     gsl_multimin_fminimizer *sfm = NULL;
                   15755:     gsl_vector *ss, *x;
                   15756:     gsl_multimin_function minex_func;
                   15757: 
                   15758:     /* Initial vertex size vector */
                   15759:     ss = gsl_vector_alloc (NDIM);
                   15760:     
                   15761:     if (ss == NULL){
                   15762:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   15763:     }
                   15764:     /* Set all step sizes to 1 */
                   15765:     gsl_vector_set_all (ss, 0.001);
                   15766: 
                   15767:     /* Starting point */
1.126     brouard  15768:     
1.136     brouard  15769:     x = gsl_vector_alloc (NDIM);
                   15770:     
                   15771:     if (x == NULL){
                   15772:       gsl_vector_free(ss);
                   15773:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   15774:     }
                   15775:   
                   15776:     /* Initialize method and iterate */
                   15777:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  15778:     /*     gsl_vector_set(x, 0, 0.0268); */
                   15779:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  15780:     gsl_vector_set(x, 0, p[1]);
                   15781:     gsl_vector_set(x, 1, p[2]);
                   15782: 
                   15783:     minex_func.f = &gompertz_f;
                   15784:     minex_func.n = NDIM;
                   15785:     minex_func.params = (void *)&p; /* ??? */
                   15786:     
                   15787:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   15788:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   15789:     
                   15790:     printf("Iterations beginning .....\n\n");
                   15791:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   15792: 
                   15793:     iteri=0;
                   15794:     while (rval == GSL_CONTINUE){
                   15795:       iteri++;
                   15796:       status = gsl_multimin_fminimizer_iterate(sfm);
                   15797:       
                   15798:       if (status) printf("error: %s\n", gsl_strerror (status));
                   15799:       fflush(0);
                   15800:       
                   15801:       if (status) 
                   15802:         break;
                   15803:       
                   15804:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   15805:       ssval = gsl_multimin_fminimizer_size (sfm);
                   15806:       
                   15807:       if (rval == GSL_SUCCESS)
                   15808:         printf ("converged to a local maximum at\n");
                   15809:       
                   15810:       printf("%5d ", iteri);
                   15811:       for (it = 0; it < NDIM; it++){
                   15812:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   15813:       }
                   15814:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   15815:     }
                   15816:     
                   15817:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   15818:     
                   15819:     gsl_vector_free(x); /* initial values */
                   15820:     gsl_vector_free(ss); /* inital step size */
                   15821:     for (it=0; it<NDIM; it++){
                   15822:       p[it+1]=gsl_vector_get(sfm->x,it);
                   15823:       fprintf(ficrespow," %.12lf", p[it]);
                   15824:     }
                   15825:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   15826: #endif
                   15827: #ifdef POWELL
1.361   ! brouard  15828: #ifdef LINMINORIGINAL
        !          15829: #else /* LINMINORIGINAL */
        !          15830:   
        !          15831:   flatdir=ivector(1,npar); 
        !          15832:   for (j=1;j<=npar;j++) flatdir[j]=0; 
        !          15833: #endif /*LINMINORIGINAL */
1.136     brouard  15834:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   15835: #endif  
1.126     brouard  15836:     fclose(ficrespow);
1.361   ! brouard  15837: #ifdef LINMINORIGINAL
        !          15838: #else
        !          15839:       free_ivector(flatdir,1,npar); 
        !          15840: #endif  /* LINMINORIGINAL*/
1.126     brouard  15841:     
1.203     brouard  15842:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  15843: 
                   15844:     for(i=1; i <=NDIM; i++)
                   15845:       for(j=i+1;j<=NDIM;j++)
1.359     brouard  15846:        matcov[i][j]=matcov[j][i];
1.126     brouard  15847:     
                   15848:     printf("\nCovariance matrix\n ");
1.203     brouard  15849:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  15850:     for(i=1; i <=NDIM; i++) {
                   15851:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  15852:                                printf("%f ",matcov[i][j]);
                   15853:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  15854:       }
1.203     brouard  15855:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  15856:     }
                   15857:     
                   15858:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  15859:     for (i=1;i<=NDIM;i++) {
1.126     brouard  15860:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  15861:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   15862:     }
1.302     brouard  15863:     lsurv=vector(agegomp,AGESUP);
                   15864:     lpop=vector(agegomp,AGESUP);
                   15865:     tpop=vector(agegomp,AGESUP);
1.126     brouard  15866:     lsurv[agegomp]=100000;
                   15867:     
                   15868:     for (k=agegomp;k<=AGESUP;k++) {
                   15869:       agemortsup=k;
                   15870:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   15871:     }
                   15872:     
                   15873:     for (k=agegomp;k<agemortsup;k++)
                   15874:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   15875:     
                   15876:     for (k=agegomp;k<agemortsup;k++){
                   15877:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   15878:       sumlpop=sumlpop+lpop[k];
                   15879:     }
                   15880:     
                   15881:     tpop[agegomp]=sumlpop;
                   15882:     for (k=agegomp;k<(agemortsup-3);k++){
                   15883:       /*  tpop[k+1]=2;*/
                   15884:       tpop[k+1]=tpop[k]-lpop[k];
                   15885:     }
                   15886:     
                   15887:     
                   15888:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   15889:     for (k=agegomp;k<(agemortsup-2);k++) 
                   15890:       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]);
                   15891:     
                   15892:     
                   15893:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  15894:                ageminpar=50;
                   15895:                agemaxpar=100;
1.194     brouard  15896:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   15897:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15898: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15899: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15900:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15901: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15902: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  15903:     }else{
                   15904:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   15905:                        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  15906:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  15907:                }
1.201     brouard  15908:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  15909:                     stepm, weightopt,\
                   15910:                     model,imx,p,matcov,agemortsup);
                   15911:     
1.302     brouard  15912:     free_vector(lsurv,agegomp,AGESUP);
                   15913:     free_vector(lpop,agegomp,AGESUP);
                   15914:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  15915:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  15916:     free_ivector(dcwave,firstobs,lastobs);
                   15917:     free_vector(agecens,firstobs,lastobs);
                   15918:     free_vector(ageexmed,firstobs,lastobs);
                   15919:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  15920: #ifdef GSL
1.136     brouard  15921: #endif
1.186     brouard  15922:   } /* Endof if mle==-3 mortality only */
1.205     brouard  15923:   /* Standard  */
                   15924:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   15925:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15926:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  15927:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  15928:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   15929:     for (k=1; k<=npar;k++)
                   15930:       printf(" %d %8.5f",k,p[k]);
                   15931:     printf("\n");
1.205     brouard  15932:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   15933:       /* mlikeli uses func not funcone */
1.247     brouard  15934:       /* for(i=1;i<nlstate;i++){ */
                   15935:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15936:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15937:       /* } */
1.205     brouard  15938:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   15939:     }
                   15940:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   15941:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15942:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   15943:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15944:     }
                   15945:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  15946:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15947:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  15948:           /* exit(0); */
1.126     brouard  15949:     for (k=1; k<=npar;k++)
                   15950:       printf(" %d %8.5f",k,p[k]);
                   15951:     printf("\n");
                   15952:     
                   15953:     /*--------- results files --------------*/
1.283     brouard  15954:     /* 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  15955:     
                   15956:     
                   15957:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15958:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  15959:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15960: 
                   15961:     printf("#model=  1      +     age ");
                   15962:     fprintf(ficres,"#model=  1      +     age ");
                   15963:     fprintf(ficlog,"#model=  1      +     age ");
                   15964:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   15965: </ul>", model);
                   15966: 
                   15967:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   15968:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   15969:     if(nagesqr==1){
                   15970:       printf("  + age*age  ");
                   15971:       fprintf(ficres,"  + age*age  ");
                   15972:       fprintf(ficlog,"  + age*age  ");
                   15973:       fprintf(fichtm, "<th>+ age*age</th>");
                   15974:     }
                   15975:     for(j=1;j <=ncovmodel-2;j++){
                   15976:       if(Typevar[j]==0) {
                   15977:        printf("  +      V%d  ",Tvar[j]);
                   15978:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   15979:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   15980:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   15981:       }else if(Typevar[j]==1) {
                   15982:        printf("  +    V%d*age ",Tvar[j]);
                   15983:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   15984:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   15985:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   15986:       }else if(Typevar[j]==2) {
                   15987:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15988:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15989:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15990:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  15991:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   15992:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15993:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15994:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15995:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  15996:       }
                   15997:     }
                   15998:     printf("\n");
                   15999:     fprintf(ficres,"\n");
                   16000:     fprintf(ficlog,"\n");
                   16001:     fprintf(fichtm, "</tr>");
                   16002:     fprintf(fichtm, "\n");
                   16003:     
                   16004:     
1.126     brouard  16005:     for(i=1,jk=1; i <=nlstate; i++){
                   16006:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  16007:        if (k != i) {
1.319     brouard  16008:          fprintf(fichtm, "<tr>");
1.225     brouard  16009:          printf("%d%d ",i,k);
                   16010:          fprintf(ficlog,"%d%d ",i,k);
                   16011:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  16012:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16013:          for(j=1; j <=ncovmodel; j++){
                   16014:            printf("%12.7f ",p[jk]);
                   16015:            fprintf(ficlog,"%12.7f ",p[jk]);
                   16016:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  16017:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  16018:            jk++; 
                   16019:          }
                   16020:          printf("\n");
                   16021:          fprintf(ficlog,"\n");
                   16022:          fprintf(ficres,"\n");
1.319     brouard  16023:          fprintf(fichtm, "</tr>\n");
1.225     brouard  16024:        }
1.126     brouard  16025:       }
                   16026:     }
1.319     brouard  16027:     /* fprintf(fichtm,"</tr>\n"); */
                   16028:     fprintf(fichtm,"</table>\n");
                   16029:     fprintf(fichtm, "\n");
                   16030: 
1.203     brouard  16031:     if(mle != 0){
                   16032:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  16033:       ftolhess=ftol; /* Usually correct */
1.203     brouard  16034:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   16035:       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");
                   16036:       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  16037:       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  16038:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   16039:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16040:       if(nagesqr==1){
                   16041:        printf("  + age*age  ");
                   16042:        fprintf(ficres,"  + age*age  ");
                   16043:        fprintf(ficlog,"  + age*age  ");
                   16044:        fprintf(fichtm, "<th>+ age*age</th>");
                   16045:       }
                   16046:       for(j=1;j <=ncovmodel-2;j++){
                   16047:        if(Typevar[j]==0) {
                   16048:          printf("  +      V%d  ",Tvar[j]);
                   16049:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16050:        }else if(Typevar[j]==1) {
                   16051:          printf("  +    V%d*age ",Tvar[j]);
                   16052:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16053:        }else if(Typevar[j]==2) {
                   16054:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16055:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   16056:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16057:        }
                   16058:       }
                   16059:       fprintf(fichtm, "</tr>\n");
                   16060:  
1.203     brouard  16061:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  16062:        for(k=1; k <=(nlstate+ndeath); k++){
                   16063:          if (k != i) {
1.319     brouard  16064:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  16065:            printf("%d%d ",i,k);
                   16066:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  16067:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16068:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  16069:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  16070:              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]));
                   16071:              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  16072:              if(fabs(wald) > 1.96){
1.321     brouard  16073:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  16074:              }else{
                   16075:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   16076:              }
1.324     brouard  16077:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  16078:              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  16079:              jk++; 
                   16080:            }
                   16081:            printf("\n");
                   16082:            fprintf(ficlog,"\n");
1.319     brouard  16083:            fprintf(fichtm, "</tr>\n");
1.225     brouard  16084:          }
                   16085:        }
1.193     brouard  16086:       }
1.203     brouard  16087:     } /* end of hesscov and Wald tests */
1.319     brouard  16088:     fprintf(fichtm,"</table>\n");
1.225     brouard  16089:     
1.203     brouard  16090:     /*  */
1.126     brouard  16091:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   16092:     printf("# Scales (for hessian or gradient estimation)\n");
                   16093:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   16094:     for(i=1,jk=1; i <=nlstate; i++){
                   16095:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  16096:        if (j!=i) {
                   16097:          fprintf(ficres,"%1d%1d",i,j);
                   16098:          printf("%1d%1d",i,j);
                   16099:          fprintf(ficlog,"%1d%1d",i,j);
                   16100:          for(k=1; k<=ncovmodel;k++){
                   16101:            printf(" %.5e",delti[jk]);
                   16102:            fprintf(ficlog," %.5e",delti[jk]);
                   16103:            fprintf(ficres," %.5e",delti[jk]);
                   16104:            jk++;
                   16105:          }
                   16106:          printf("\n");
                   16107:          fprintf(ficlog,"\n");
                   16108:          fprintf(ficres,"\n");
                   16109:        }
1.126     brouard  16110:       }
                   16111:     }
                   16112:     
                   16113:     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  16114:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  16115:       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");
                   16116:     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");
                   16117:     /* # 121 Var(a12)\n\ */
                   16118:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   16119:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   16120:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   16121:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   16122:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   16123:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   16124:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   16125:     
                   16126:     
                   16127:     /* Just to have a covariance matrix which will be more understandable
                   16128:        even is we still don't want to manage dictionary of variables
                   16129:     */
                   16130:     for(itimes=1;itimes<=2;itimes++){
                   16131:       jj=0;
                   16132:       for(i=1; i <=nlstate; i++){
1.225     brouard  16133:        for(j=1; j <=nlstate+ndeath; j++){
                   16134:          if(j==i) continue;
                   16135:          for(k=1; k<=ncovmodel;k++){
                   16136:            jj++;
                   16137:            ca[0]= k+'a'-1;ca[1]='\0';
                   16138:            if(itimes==1){
                   16139:              if(mle>=1)
                   16140:                printf("#%1d%1d%d",i,j,k);
                   16141:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   16142:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   16143:            }else{
                   16144:              if(mle>=1)
                   16145:                printf("%1d%1d%d",i,j,k);
                   16146:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   16147:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   16148:            }
                   16149:            ll=0;
                   16150:            for(li=1;li <=nlstate; li++){
                   16151:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   16152:                if(lj==li) continue;
                   16153:                for(lk=1;lk<=ncovmodel;lk++){
                   16154:                  ll++;
                   16155:                  if(ll<=jj){
                   16156:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   16157:                    if(ll<jj){
                   16158:                      if(itimes==1){
                   16159:                        if(mle>=1)
                   16160:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16161:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16162:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16163:                      }else{
                   16164:                        if(mle>=1)
                   16165:                          printf(" %.5e",matcov[jj][ll]); 
                   16166:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   16167:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   16168:                      }
                   16169:                    }else{
                   16170:                      if(itimes==1){
                   16171:                        if(mle>=1)
                   16172:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   16173:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   16174:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   16175:                      }else{
                   16176:                        if(mle>=1)
                   16177:                          printf(" %.7e",matcov[jj][ll]); 
                   16178:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   16179:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   16180:                      }
                   16181:                    }
                   16182:                  }
                   16183:                } /* end lk */
                   16184:              } /* end lj */
                   16185:            } /* end li */
                   16186:            if(mle>=1)
                   16187:              printf("\n");
                   16188:            fprintf(ficlog,"\n");
                   16189:            fprintf(ficres,"\n");
                   16190:            numlinepar++;
                   16191:          } /* end k*/
                   16192:        } /*end j */
1.126     brouard  16193:       } /* end i */
                   16194:     } /* end itimes */
                   16195:     
                   16196:     fflush(ficlog);
                   16197:     fflush(ficres);
1.225     brouard  16198:     while(fgets(line, MAXLINE, ficpar)) {
                   16199:       /* If line starts with a # it is a comment */
                   16200:       if (line[0] == '#') {
                   16201:        numlinepar++;
                   16202:        fputs(line,stdout);
                   16203:        fputs(line,ficparo);
                   16204:        fputs(line,ficlog);
1.299     brouard  16205:        fputs(line,ficres);
1.225     brouard  16206:        continue;
                   16207:       }else
                   16208:        break;
                   16209:     }
                   16210:     
1.209     brouard  16211:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   16212:     /*   ungetc(c,ficpar); */
                   16213:     /*   fgets(line, MAXLINE, ficpar); */
                   16214:     /*   fputs(line,stdout); */
                   16215:     /*   fputs(line,ficparo); */
                   16216:     /* } */
                   16217:     /* ungetc(c,ficpar); */
1.126     brouard  16218:     
                   16219:     estepm=0;
1.209     brouard  16220:     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  16221:       
                   16222:       if (num_filled != 6) {
                   16223:        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);
                   16224:        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);
                   16225:        goto end;
                   16226:       }
                   16227:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   16228:     }
                   16229:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   16230:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   16231:     
1.209     brouard  16232:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  16233:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   16234:     if (fage <= 2) {
                   16235:       bage = ageminpar;
                   16236:       fage = agemaxpar;
                   16237:     }
                   16238:     
                   16239:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  16240:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   16241:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  16242:                
1.186     brouard  16243:     /* Other stuffs, more or less useful */    
1.254     brouard  16244:     while(fgets(line, MAXLINE, ficpar)) {
                   16245:       /* If line starts with a # it is a comment */
                   16246:       if (line[0] == '#') {
                   16247:        numlinepar++;
                   16248:        fputs(line,stdout);
                   16249:        fputs(line,ficparo);
                   16250:        fputs(line,ficlog);
1.299     brouard  16251:        fputs(line,ficres);
1.254     brouard  16252:        continue;
                   16253:       }else
                   16254:        break;
                   16255:     }
                   16256: 
                   16257:     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){
                   16258:       
                   16259:       if (num_filled != 7) {
                   16260:        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);
                   16261:        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);
                   16262:        goto end;
                   16263:       }
                   16264:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   16265:       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);
                   16266:       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);
                   16267:       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  16268:     }
1.254     brouard  16269: 
                   16270:     while(fgets(line, MAXLINE, ficpar)) {
                   16271:       /* If line starts with a # it is a comment */
                   16272:       if (line[0] == '#') {
                   16273:        numlinepar++;
                   16274:        fputs(line,stdout);
                   16275:        fputs(line,ficparo);
                   16276:        fputs(line,ficlog);
1.299     brouard  16277:        fputs(line,ficres);
1.254     brouard  16278:        continue;
                   16279:       }else
                   16280:        break;
1.126     brouard  16281:     }
                   16282:     
                   16283:     
                   16284:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   16285:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   16286:     
1.254     brouard  16287:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   16288:       if (num_filled != 1) {
                   16289:        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);
                   16290:        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);
                   16291:        goto end;
                   16292:       }
                   16293:       printf("pop_based=%d\n",popbased);
                   16294:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   16295:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   16296:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   16297:     }
                   16298:      
1.258     brouard  16299:     /* Results */
1.359     brouard  16300:     /* Value of covariate in each resultine will be computed (if product) and sorted according to model rank */
1.332     brouard  16301:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   16302:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  16303:     endishere=0;
1.258     brouard  16304:     nresult=0;
1.308     brouard  16305:     parameterline=0;
1.258     brouard  16306:     do{
                   16307:       if(!fgets(line, MAXLINE, ficpar)){
                   16308:        endishere=1;
1.308     brouard  16309:        parameterline=15;
1.258     brouard  16310:       }else if (line[0] == '#') {
                   16311:        /* If line starts with a # it is a comment */
1.254     brouard  16312:        numlinepar++;
                   16313:        fputs(line,stdout);
                   16314:        fputs(line,ficparo);
                   16315:        fputs(line,ficlog);
1.299     brouard  16316:        fputs(line,ficres);
1.254     brouard  16317:        continue;
1.258     brouard  16318:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   16319:        parameterline=11;
1.296     brouard  16320:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  16321:        parameterline=12;
1.307     brouard  16322:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  16323:        parameterline=13;
1.307     brouard  16324:       }
1.258     brouard  16325:       else{
                   16326:        parameterline=14;
1.254     brouard  16327:       }
1.308     brouard  16328:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  16329:       case 11:
1.296     brouard  16330:        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)){
                   16331:                  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  16332:          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);
                   16333:          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);
                   16334:          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);
                   16335:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  16336:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   16337:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  16338:           prvforecast = 1;
                   16339:        } 
                   16340:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  16341:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16342:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16343:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  16344:           prvforecast = 2;
                   16345:        }
                   16346:        else {
                   16347:          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);
                   16348:          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);
                   16349:          goto end;
1.258     brouard  16350:        }
1.254     brouard  16351:        break;
1.258     brouard  16352:       case 12:
1.296     brouard  16353:        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)){
                   16354:           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);
                   16355:          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);
                   16356:          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);
                   16357:          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);
                   16358:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  16359:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   16360:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  16361:           prvbackcast = 1;
                   16362:        } 
                   16363:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  16364:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16365:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16366:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  16367:           prvbackcast = 2;
                   16368:        }
                   16369:        else {
                   16370:          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);
                   16371:          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);
                   16372:          goto end;
1.258     brouard  16373:        }
1.230     brouard  16374:        break;
1.258     brouard  16375:       case 13:
1.332     brouard  16376:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  16377:        nresult++; /* Sum of resultlines */
1.342     brouard  16378:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  16379:        /* removefirstspace(&resultlineori); */
                   16380:        
                   16381:        if(strstr(resultlineori,"v") !=0){
                   16382:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   16383:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   16384:          return 1;
                   16385:        }
                   16386:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  16387:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  16388:        if(nresult > MAXRESULTLINESPONE-1){
                   16389:          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);
                   16390:          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  16391:          goto end;
                   16392:        }
1.332     brouard  16393:        
1.310     brouard  16394:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  16395:          fprintf(ficparo,"result: %s\n",resultline);
                   16396:          fprintf(ficres,"result: %s\n",resultline);
                   16397:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  16398:        } else
                   16399:          goto end;
1.307     brouard  16400:        break;
                   16401:       case 14:
                   16402:        printf("Error: Unknown command '%s'\n",line);
                   16403:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  16404:        if(line[0] == ' ' || line[0] == '\n'){
                   16405:          printf("It should not be an empty line '%s'\n",line);
                   16406:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   16407:        }         
1.307     brouard  16408:        if(ncovmodel >=2 && nresult==0 ){
                   16409:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   16410:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  16411:        }
1.307     brouard  16412:        /* goto end; */
                   16413:        break;
1.308     brouard  16414:       case 15:
                   16415:        printf("End of resultlines.\n");
                   16416:        fprintf(ficlog,"End of resultlines.\n");
                   16417:        break;
                   16418:       default: /* parameterline =0 */
1.307     brouard  16419:        nresult=1;
                   16420:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  16421:       } /* End switch parameterline */
                   16422:     }while(endishere==0); /* End do */
1.126     brouard  16423:     
1.230     brouard  16424:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  16425:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  16426:     
                   16427:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  16428:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  16429:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16430: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16431: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  16432:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16433: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16434: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  16435:     }else{
1.270     brouard  16436:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  16437:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   16438:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   16439:       if(prvforecast==1){
                   16440:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   16441:         jprojd=jproj1;
                   16442:         mprojd=mproj1;
                   16443:         anprojd=anproj1;
                   16444:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   16445:         jprojf=jproj2;
                   16446:         mprojf=mproj2;
                   16447:         anprojf=anproj2;
                   16448:       } else if(prvforecast == 2){
                   16449:         dateprojd=dateintmean;
                   16450:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   16451:         dateprojf=dateintmean+yrfproj;
                   16452:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   16453:       }
                   16454:       if(prvbackcast==1){
                   16455:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   16456:         jbackd=jback1;
                   16457:         mbackd=mback1;
                   16458:         anbackd=anback1;
                   16459:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   16460:         jbackf=jback2;
                   16461:         mbackf=mback2;
                   16462:         anbackf=anback2;
                   16463:       } else if(prvbackcast == 2){
                   16464:         datebackd=dateintmean;
                   16465:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   16466:         datebackf=dateintmean-yrbproj;
                   16467:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   16468:       }
                   16469:       
1.350     brouard  16470:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  16471:     }
                   16472:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  16473:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   16474:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  16475:                
1.225     brouard  16476:     /*------------ free_vector  -------------*/
                   16477:     /*  chdir(path); */
1.220     brouard  16478:                
1.215     brouard  16479:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   16480:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   16481:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   16482:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  16483:     free_lvector(num,firstobs,lastobs);
                   16484:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  16485:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   16486:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   16487:     fclose(ficparo);
                   16488:     fclose(ficres);
1.220     brouard  16489:                
                   16490:                
1.186     brouard  16491:     /* Other results (useful)*/
1.220     brouard  16492:                
                   16493:                
1.126     brouard  16494:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  16495:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   16496:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  16497:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  16498:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  16499:     fclose(ficrespl);
                   16500: 
                   16501:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  16502:     /*#include "hpijx.h"*/
1.332     brouard  16503:     /** 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?*/
                   16504:     /* calls hpxij with combination k */
1.180     brouard  16505:     hPijx(p, bage, fage);
1.145     brouard  16506:     fclose(ficrespij);
1.227     brouard  16507:     
1.220     brouard  16508:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  16509:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  16510:     k=1;
1.126     brouard  16511:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  16512:     
1.269     brouard  16513:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   16514:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16515:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  16516:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  16517:        for(k=1;k<=ncovcombmax;k++)
                   16518:          probs[i][j][k]=0.;
1.269     brouard  16519:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   16520:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  16521:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  16522:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16523:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  16524:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  16525:          for(k=1;k<=ncovcombmax;k++)
                   16526:            mobaverages[i][j][k]=0.;
1.219     brouard  16527:       mobaverage=mobaverages;
                   16528:       if (mobilav!=0) {
1.235     brouard  16529:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  16530:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  16531:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   16532:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   16533:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   16534:        }
1.269     brouard  16535:       } else if (mobilavproj !=0) {
1.235     brouard  16536:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  16537:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  16538:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   16539:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16540:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16541:        }
1.269     brouard  16542:       }else{
                   16543:        printf("Internal error moving average\n");
                   16544:        fflush(stdout);
                   16545:        exit(1);
1.219     brouard  16546:       }
                   16547:     }/* end if moving average */
1.227     brouard  16548:     
1.126     brouard  16549:     /*---------- Forecasting ------------------*/
1.296     brouard  16550:     if(prevfcast==1){ 
                   16551:       /*   /\*    if(stepm ==1){*\/ */
                   16552:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16553:       /*This done previously after freqsummary.*/
                   16554:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   16555:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   16556:       
                   16557:       /* } else if (prvforecast==2){ */
                   16558:       /*   /\*    if(stepm ==1){*\/ */
                   16559:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16560:       /* } */
                   16561:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   16562:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  16563:     }
1.269     brouard  16564: 
1.296     brouard  16565:     /* Prevbcasting */
                   16566:     if(prevbcast==1){
1.219     brouard  16567:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16568:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16569:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   16570: 
                   16571:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   16572: 
                   16573:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  16574: 
1.219     brouard  16575:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   16576:       fclose(ficresplb);
                   16577: 
1.222     brouard  16578:       hBijx(p, bage, fage, mobaverage);
                   16579:       fclose(ficrespijb);
1.219     brouard  16580: 
1.296     brouard  16581:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   16582:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   16583:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   16584:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   16585:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   16586:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   16587: 
                   16588:       
1.269     brouard  16589:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16590: 
                   16591:       
1.269     brouard  16592:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  16593:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16594:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16595:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  16596:     }    /* end  Prevbcasting */
1.268     brouard  16597:  
1.186     brouard  16598:  
                   16599:     /* ------ Other prevalence ratios------------ */
1.126     brouard  16600: 
1.215     brouard  16601:     free_ivector(wav,1,imx);
                   16602:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   16603:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   16604:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  16605:                
                   16606:                
1.127     brouard  16607:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  16608:                
1.201     brouard  16609:     strcpy(filerese,"E_");
                   16610:     strcat(filerese,fileresu);
1.126     brouard  16611:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   16612:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16613:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16614:     }
1.208     brouard  16615:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   16616:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  16617: 
                   16618:     pstamp(ficreseij);
1.219     brouard  16619:                
1.351     brouard  16620:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   16621:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  16622:     
1.351     brouard  16623:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   16624:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   16625:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   16626:       /*       continue; */
1.219     brouard  16627:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  16628:       printf("\n#****** ");
1.351     brouard  16629:       for(j=1;j<=cptcovs;j++){
                   16630:       /* for(j=1;j<=cptcoveff;j++) { */
                   16631:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16632:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16633:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16634:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  16635:       }
                   16636:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  16637:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   16638:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  16639:       }
                   16640:       fprintf(ficreseij,"******\n");
1.235     brouard  16641:       printf("******\n");
1.219     brouard  16642:       
                   16643:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16644:       oldm=oldms;savm=savms;
1.330     brouard  16645:       /* 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  16646:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  16647:       
1.219     brouard  16648:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  16649:     }
                   16650:     fclose(ficreseij);
1.208     brouard  16651:     printf("done evsij\n");fflush(stdout);
                   16652:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  16653: 
1.218     brouard  16654:                
1.227     brouard  16655:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  16656:     /* Should be moved in a function */                
1.201     brouard  16657:     strcpy(filerest,"T_");
                   16658:     strcat(filerest,fileresu);
1.127     brouard  16659:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   16660:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   16661:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   16662:     }
1.208     brouard  16663:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   16664:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  16665:     strcpy(fileresstde,"STDE_");
                   16666:     strcat(fileresstde,fileresu);
1.126     brouard  16667:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  16668:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   16669:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  16670:     }
1.227     brouard  16671:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   16672:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  16673: 
1.201     brouard  16674:     strcpy(filerescve,"CVE_");
                   16675:     strcat(filerescve,fileresu);
1.126     brouard  16676:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  16677:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   16678:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  16679:     }
1.227     brouard  16680:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   16681:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  16682: 
1.201     brouard  16683:     strcpy(fileresv,"V_");
                   16684:     strcat(fileresv,fileresu);
1.126     brouard  16685:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   16686:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16687:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16688:     }
1.227     brouard  16689:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   16690:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  16691: 
1.235     brouard  16692:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   16693:     if (cptcovn < 1){i1=1;}
                   16694:     
1.334     brouard  16695:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   16696:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   16697:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   16698:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   16699:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   16700:       /* */
                   16701:       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  16702:        continue;
1.359     brouard  16703:       printf("\n# model=1+age+%s \n#****** Result for:", model);  /* HERE model is empty */
                   16704:       fprintf(ficrest,"\n# model=1+age+%s \n#****** Result for:", model);
                   16705:       fprintf(ficlog,"\n# model=1+age+%s \n#****** Result for:", model);
1.334     brouard  16706:       /* It might not be a good idea to mix dummies and quantitative */
                   16707:       /* 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 *\/ */
                   16708:       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 */
                   16709:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   16710:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   16711:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   16712:         * (V5 is quanti) V4 and V3 are dummies
                   16713:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   16714:         *                                                              l=1 l=2
                   16715:         *                                                           k=1  1   1   0   0
                   16716:         *                                                           k=2  2   1   1   0
                   16717:         *                                                           k=3 [1] [2]  0   1
                   16718:         *                                                           k=4  2   2   1   1
                   16719:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   16720:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   16721:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   16722:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   16723:         */
                   16724:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   16725:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   16726: /* We give up with the combinations!! */
1.342     brouard  16727:        /* if(debugILK) */
                   16728:        /*   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  16729: 
                   16730:        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  16731:          /* 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] */
                   16732:          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  */
                   16733:          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  */
                   16734:          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  16735:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16736:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16737:          }else{
                   16738:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16739:          }
                   16740:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16741:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16742:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   16743:          /* For each selected (single) quantitative value */
1.337     brouard  16744:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16745:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16746:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  16747:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16748:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16749:          }else{
                   16750:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16751:          }
                   16752:        }else{
                   16753:          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 */
                   16754:          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 */
                   16755:          exit(1);
                   16756:        }
1.335     brouard  16757:       } /* End loop for each variable in the resultline */
1.334     brouard  16758:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   16759:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   16760:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16761:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16762:       /* }      */
1.208     brouard  16763:       fprintf(ficrest,"******\n");
1.227     brouard  16764:       fprintf(ficlog,"******\n");
                   16765:       printf("******\n");
1.208     brouard  16766:       
                   16767:       fprintf(ficresstdeij,"\n#****** ");
                   16768:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  16769:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   16770:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  16771:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  16772:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16773:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16774:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16775:       }
                   16776:       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  16777:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   16778:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  16779:       }        
1.208     brouard  16780:       fprintf(ficresstdeij,"******\n");
                   16781:       fprintf(ficrescveij,"******\n");
                   16782:       
                   16783:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  16784:       /* pstamp(ficresvij); */
1.225     brouard  16785:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  16786:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16787:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  16788:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  16789:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  16790:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  16791:       }        
1.208     brouard  16792:       fprintf(ficresvij,"******\n");
                   16793:       
                   16794:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16795:       oldm=oldms;savm=savms;
1.235     brouard  16796:       printf(" cvevsij ");
                   16797:       fprintf(ficlog, " cvevsij ");
                   16798:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  16799:       printf(" end cvevsij \n ");
                   16800:       fprintf(ficlog, " end cvevsij \n ");
                   16801:       
                   16802:       /*
                   16803:        */
                   16804:       /* goto endfree; */
                   16805:       
                   16806:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16807:       pstamp(ficrest);
                   16808:       
1.269     brouard  16809:       epj=vector(1,nlstate+1);
1.208     brouard  16810:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  16811:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   16812:        cptcod= 0; /* To be deleted */
1.360     brouard  16813:        printf("varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
                   16814:        fprintf(ficlog, "varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
1.361   ! brouard  16815:        /* Call to varevsij to get cov(e.i, e.j)= vareij[i][j][(int)age]=sum_h sum_k trgrad(h_p.i) V(theta) grad(k_p.k) Equation 20 */
        !          16816:        /* Depending of popbased which changes the prevalences, either cross-sectional or period */
1.235     brouard  16817:        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.360     brouard  16818:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each state\n\
                   16819: #  (these are weighted average of eij where weights are ");
1.227     brouard  16820:        if(vpopbased==1)
1.360     brouard  16821:          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);
1.227     brouard  16822:        else
1.360     brouard  16823:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each state) \n");
                   16824:        fprintf(ficrest,"# with proportions of time spent in each state with standard error (on the right of the table.\n ");
1.335     brouard  16825:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  16826:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
1.360     brouard  16827:        for (i=1;i<=nlstate;i++) fprintf(ficrest," %% e.%d/e.. (std) ",i);
1.227     brouard  16828:        fprintf(ficrest,"\n");
                   16829:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  16830:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   16831:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  16832:        for(age=bage; age <=fage ;age++){
1.235     brouard  16833:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  16834:          if (vpopbased==1) {
                   16835:            if(mobilav ==0){
                   16836:              for(i=1; i<=nlstate;i++)
                   16837:                prlim[i][i]=probs[(int)age][i][k];
                   16838:            }else{ /* mobilav */ 
                   16839:              for(i=1; i<=nlstate;i++)
                   16840:                prlim[i][i]=mobaverage[(int)age][i][k];
                   16841:            }
                   16842:          }
1.219     brouard  16843:          
1.227     brouard  16844:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   16845:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   16846:          /* printf(" age %4.0f ",age); */
                   16847:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   16848:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   16849:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   16850:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   16851:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   16852:            }
1.361   ! brouard  16853:            epj[nlstate+1] +=epj[j]; /* epp=sum_j epj = sum_j sum_i w_i e_ij */
1.227     brouard  16854:          }
                   16855:          /* printf(" age %4.0f \n",age); */
1.219     brouard  16856:          
1.361   ! brouard  16857:          for(i=1, vepp=0.;i <=nlstate;i++)  /* Variance of total life expectancy e.. */
1.227     brouard  16858:            for(j=1;j <=nlstate;j++)
1.361   ! brouard  16859:              vepp += vareij[i][j][(int)age]; /* sum_i sum_j cov(e.i, e.j) = var(e..) */
1.227     brouard  16860:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
1.361   ! brouard  16861:          /* vareij[i][j] is the covariance  cov(e.i, e.j) and vareij[j][j] is the variance  of e.j  */
1.227     brouard  16862:          for(j=1;j <=nlstate;j++){
                   16863:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   16864:          }
1.360     brouard  16865:          /* And proportion of time spent in state j */
                   16866:          /* $$ E[r(X,Y)-E(r(X,Y))]^2=[\frac{1}{\mu_y} -\frac{\mu_x}{{\mu_y}^2}]' Var(X,Y)[\frac{1}{\mu_y} -\frac{\mu_x}{{\mu_y}^2}]$$ */
1.361   ! brouard  16867:           /* \frac{\mu_x^2}{\mu_y^2} ( \frac{\sigma^2_x}{\mu_x^2}-2\frac{\sigma_{xy}}{\mu_x\mu_y} +\frac{\sigma^2_y}{\mu_y^2}) */
        !          16868:          /* \frac{e_{.i}^2}{e_{..}^2} ( \frac{\Var e_{.i}}{e_{.i}^2}-2\frac{\Var e_{.i} + \sum_{j\ne i} \Cov e_{.j},e_{.i}}{e_{.i}e_{..}} +\frac{\Var e_{..}}{e_{..}^2})*/
        !          16869:          /*\mu_x = epj[j], \sigma^2_x = vareij[j][j][(int)age] and \mu_y=epj[nlstate+1], \sigma^2_y=vepp \sigmaxy= */
        !          16870:          /* vareij[j][j][(int)age]/epj[nlstate+1]^2 + vepp/epj[nlstate+1]^4 */
1.360     brouard  16871:          for(j=1;j <=nlstate;j++){
                   16872:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[j]/epj[j]/epj[j]/epj[j] )); */
1.361   ! brouard  16873:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[j]/epj[j]/epj[j]/epj[j] )); */
        !          16874:            
        !          16875:            for(i=1,stdpercent=0.;i<=nlstate;i++){ /* Computing cov(e..,e.j)=cov(sum_i e.i,e.j)=sum_i cov(e.i, e.j) */
        !          16876:              stdpercent += vareij[i][j][(int)age];
        !          16877:            }
        !          16878:            stdpercent= epj[j]*epj[j]/epj[nlstate+1]/epj[nlstate+1]* (vareij[j][j][(int)age]/epj[j]/epj[j]-2.*stdpercent/epj[j]/epj[nlstate+1]+ vepp/epj[nlstate+1]/epj[nlstate+1]);
        !          16879:            /* stdpercent= epj[j]*epj[j]/epj[nlstate+1]/epj[nlstate+1]*(vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[nlstate+1]/epj[nlstate+1]); */ /* Without covariance */
        !          16880:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[nlstate+1]/epj[nlstate+1] + epj[j]*epj[j]*vepp/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1] )); */
        !          16881:            fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt(stdpercent));
1.360     brouard  16882:          }
1.227     brouard  16883:          fprintf(ficrest,"\n");
                   16884:        }
1.208     brouard  16885:       } /* End vpopbased */
1.269     brouard  16886:       free_vector(epj,1,nlstate+1);
1.208     brouard  16887:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   16888:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  16889:       printf("done selection\n");fflush(stdout);
                   16890:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  16891:       
1.335     brouard  16892:     } /* End k selection or end covariate selection for nres */
1.227     brouard  16893: 
                   16894:     printf("done State-specific expectancies\n");fflush(stdout);
                   16895:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   16896: 
1.335     brouard  16897:     /* variance-covariance of forward period prevalence */
1.269     brouard  16898:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16899: 
1.227     brouard  16900:     
1.290     brouard  16901:     free_vector(weight,firstobs,lastobs);
1.351     brouard  16902:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  16903:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  16904:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   16905:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   16906:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   16907:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  16908:     free_ivector(tab,1,NCOVMAX);
                   16909:     fclose(ficresstdeij);
                   16910:     fclose(ficrescveij);
                   16911:     fclose(ficresvij);
                   16912:     fclose(ficrest);
                   16913:     fclose(ficpar);
                   16914:     
                   16915:     
1.126     brouard  16916:     /*---------- End : free ----------------*/
1.219     brouard  16917:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  16918:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   16919:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  16920:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   16921:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  16922:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  16923:   /* endfree:*/
1.359     brouard  16924:   if(mle!=-3) free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
1.227     brouard  16925:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16926:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16927:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  16928:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   16929:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  16930:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   16931:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   16932:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  16933:   free_matrix(matcov,1,npar,1,npar);
                   16934:   free_matrix(hess,1,npar,1,npar);
                   16935:   /*free_vector(delti,1,npar);*/
                   16936:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   16937:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  16938:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  16939:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   16940:   
                   16941:   free_ivector(ncodemax,1,NCOVMAX);
                   16942:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   16943:   free_ivector(Dummy,-1,NCOVMAX);
                   16944:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  16945:   free_ivector(DummyV,-1,NCOVMAX);
                   16946:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  16947:   free_ivector(Typevar,-1,NCOVMAX);
                   16948:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  16949:   free_ivector(TvarsQ,1,NCOVMAX);
                   16950:   free_ivector(TvarsQind,1,NCOVMAX);
                   16951:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  16952:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  16953:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  16954:   free_ivector(TvarFD,1,NCOVMAX);
                   16955:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  16956:   free_ivector(TvarF,1,NCOVMAX);
                   16957:   free_ivector(TvarFind,1,NCOVMAX);
                   16958:   free_ivector(TvarV,1,NCOVMAX);
                   16959:   free_ivector(TvarVind,1,NCOVMAX);
                   16960:   free_ivector(TvarA,1,NCOVMAX);
                   16961:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  16962:   free_ivector(TvarFQ,1,NCOVMAX);
                   16963:   free_ivector(TvarFQind,1,NCOVMAX);
                   16964:   free_ivector(TvarVD,1,NCOVMAX);
                   16965:   free_ivector(TvarVDind,1,NCOVMAX);
                   16966:   free_ivector(TvarVQ,1,NCOVMAX);
                   16967:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  16968:   free_ivector(TvarAVVA,1,NCOVMAX);
                   16969:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   16970:   free_ivector(TvarVVA,1,NCOVMAX);
                   16971:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  16972:   free_ivector(TvarVV,1,NCOVMAX);
                   16973:   free_ivector(TvarVVind,1,NCOVMAX);
                   16974:   
1.230     brouard  16975:   free_ivector(Tvarsel,1,NCOVMAX);
                   16976:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  16977:   free_ivector(Tposprod,1,NCOVMAX);
                   16978:   free_ivector(Tprod,1,NCOVMAX);
                   16979:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  16980:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  16981:   free_ivector(Tage,1,NCOVMAX);
                   16982:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  16983:   free_ivector(TmodelInvind,1,NCOVMAX);
                   16984:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  16985: 
1.359     brouard  16986:   /* free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /\* Could be elsewhere ?*\/ */
1.332     brouard  16987: 
1.227     brouard  16988:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   16989:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  16990:   fflush(fichtm);
                   16991:   fflush(ficgp);
                   16992:   
1.227     brouard  16993:   
1.126     brouard  16994:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  16995:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   16996:     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  16997:   }else{
                   16998:     printf("End of Imach\n");
                   16999:     fprintf(ficlog,"End of Imach\n");
                   17000:   }
                   17001:   printf("See log file on %s\n",filelog);
                   17002:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  17003:   /*(void) gettimeofday(&end_time,&tzp);*/
                   17004:   rend_time = time(NULL);  
                   17005:   end_time = *localtime(&rend_time);
                   17006:   /* tml = *localtime(&end_time.tm_sec); */
                   17007:   strcpy(strtend,asctime(&end_time));
1.126     brouard  17008:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   17009:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  17010:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  17011:   
1.157     brouard  17012:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   17013:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   17014:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  17015:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   17016: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   17017:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17018:   fclose(fichtm);
                   17019:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17020:   fclose(fichtmcov);
                   17021:   fclose(ficgp);
                   17022:   fclose(ficlog);
                   17023:   /*------ End -----------*/
1.227     brouard  17024:   
1.281     brouard  17025: 
                   17026: /* Executes gnuplot */
1.227     brouard  17027:   
                   17028:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  17029: #ifdef WIN32
1.227     brouard  17030:   if (_chdir(pathcd) != 0)
                   17031:     printf("Can't move to directory %s!\n",path);
                   17032:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  17033: #else
1.227     brouard  17034:     if(chdir(pathcd) != 0)
                   17035:       printf("Can't move to directory %s!\n", path);
                   17036:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  17037: #endif 
1.126     brouard  17038:     printf("Current directory %s!\n",pathcd);
                   17039:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   17040:   sprintf(plotcmd,"gnuplot");
1.157     brouard  17041: #ifdef _WIN32
1.126     brouard  17042:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   17043: #endif
                   17044:   if(!stat(plotcmd,&info)){
1.158     brouard  17045:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17046:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  17047:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  17048:     }else
                   17049:       strcpy(pplotcmd,plotcmd);
1.157     brouard  17050: #ifdef __unix
1.126     brouard  17051:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   17052:     if(!stat(plotcmd,&info)){
1.158     brouard  17053:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17054:     }else
                   17055:       strcpy(pplotcmd,plotcmd);
                   17056: #endif
                   17057:   }else
                   17058:     strcpy(pplotcmd,plotcmd);
                   17059:   
                   17060:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  17061:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  17062:   strcpy(pplotcmd,plotcmd);
1.227     brouard  17063:   
1.126     brouard  17064:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  17065:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  17066:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  17067:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  17068:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  17069:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  17070:       strcpy(plotcmd,pplotcmd);
                   17071:     }
1.126     brouard  17072:   }
1.158     brouard  17073:   printf(" Successful, please wait...");
1.126     brouard  17074:   while (z[0] != 'q') {
                   17075:     /* chdir(path); */
1.154     brouard  17076:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  17077:     scanf("%s",z);
                   17078: /*     if (z[0] == 'c') system("./imach"); */
                   17079:     if (z[0] == 'e') {
1.158     brouard  17080: #ifdef __APPLE__
1.152     brouard  17081:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  17082: #elif __linux
                   17083:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  17084: #else
1.152     brouard  17085:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  17086: #endif
                   17087:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   17088:       system(pplotcmd);
1.126     brouard  17089:     }
                   17090:     else if (z[0] == 'g') system(plotcmd);
                   17091:     else if (z[0] == 'q') exit(0);
                   17092:   }
1.227     brouard  17093: end:
1.126     brouard  17094:   while (z[0] != 'q') {
1.195     brouard  17095:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  17096:     scanf("%s",z);
                   17097:   }
1.283     brouard  17098:   printf("End\n");
1.282     brouard  17099:   exit(0);
1.126     brouard  17100: }

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