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

1.345   ! brouard     1: /* $Id: imach.c,v 1.344 2022/09/14 19:33:30 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.345   ! brouard     4:   Revision 1.344  2022/09/14 19:33:30  brouard
        !             5:   Summary: version 0.99r40
        !             6: 
        !             7:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
        !             8: 
1.344     brouard     9:   Revision 1.343  2022/09/14 14:22:16  brouard
                     10:   Summary: version 0.99r39
                     11: 
                     12:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     13:   (fixed or time varying), using new last columns of
                     14:   ILK_parameter.txt file.
                     15: 
1.343     brouard    16:   Revision 1.342  2022/09/11 19:54:09  brouard
                     17:   Summary: 0.99r38
                     18: 
                     19:   * imach.c (Module): Adding timevarying products of any kinds,
                     20:   should work before shifting cotvar from ncovcol+nqv columns in
                     21:   order to have a correspondance between the column of cotvar and
                     22:   the id of column.
                     23:   (Module): Some cleaning and adding covariates in ILK.txt
                     24: 
1.342     brouard    25:   Revision 1.341  2022/09/11 07:58:42  brouard
                     26:   Summary: Version 0.99r38
                     27: 
                     28:   After adding change in cotvar.
                     29: 
1.341     brouard    30:   Revision 1.340  2022/09/11 07:53:11  brouard
                     31:   Summary: Version imach 0.99r37
                     32: 
                     33:   * imach.c (Module): Adding timevarying products of any kinds,
                     34:   should work before shifting cotvar from ncovcol+nqv columns in
                     35:   order to have a correspondance between the column of cotvar and
                     36:   the id of column.
                     37: 
1.340     brouard    38:   Revision 1.339  2022/09/09 17:55:22  brouard
                     39:   Summary: version 0.99r37
                     40: 
                     41:   * imach.c (Module): Many improvements for fixing products of fixed
                     42:   timevarying as well as fixed * fixed, and test with quantitative
                     43:   covariate.
                     44: 
1.339     brouard    45:   Revision 1.338  2022/09/04 17:40:33  brouard
                     46:   Summary: 0.99r36
                     47: 
                     48:   * imach.c (Module): Now the easy runs i.e. without result or
                     49:   model=1+age only did not work. The defautl combination should be 1
                     50:   and not 0 because everything hasn't been tranformed yet.
                     51: 
1.338     brouard    52:   Revision 1.337  2022/09/02 14:26:02  brouard
                     53:   Summary: version 0.99r35
                     54: 
                     55:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     56:   1+age+V1+V1*age for females and 1+age for females only
                     57:   (education=1 noweight)
                     58: 
1.337     brouard    59:   Revision 1.336  2022/08/31 09:52:36  brouard
                     60:   *** empty log message ***
                     61: 
1.336     brouard    62:   Revision 1.335  2022/08/31 08:23:16  brouard
                     63:   Summary: improvements...
                     64: 
1.335     brouard    65:   Revision 1.334  2022/08/25 09:08:41  brouard
                     66:   Summary: In progress for quantitative
                     67: 
1.334     brouard    68:   Revision 1.333  2022/08/21 09:10:30  brouard
                     69:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     70:   reassigning covariates: my first idea was that people will always
                     71:   use the first covariate V1 into the model but in fact they are
                     72:   producing data with many covariates and can use an equation model
                     73:   with some of the covariate; it means that in a model V2+V3 instead
                     74:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     75:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     76:   the equation model is restricted to two variables only (V2, V3)
                     77:   and the combination for V2 should be codtabm(k,1) instead of
                     78:   (codtabm(k,2), and the code should be
                     79:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     80:   made. All of these should be simplified once a day like we did in
                     81:   hpxij() for example by using precov[nres] which is computed in
                     82:   decoderesult for each nres of each resultline. Loop should be done
                     83:   on the equation model globally by distinguishing only product with
                     84:   age (which are changing with age) and no more on type of
                     85:   covariates, single dummies, single covariates.
                     86: 
1.333     brouard    87:   Revision 1.332  2022/08/21 09:06:25  brouard
                     88:   Summary: Version 0.99r33
                     89: 
                     90:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     91:   reassigning covariates: my first idea was that people will always
                     92:   use the first covariate V1 into the model but in fact they are
                     93:   producing data with many covariates and can use an equation model
                     94:   with some of the covariate; it means that in a model V2+V3 instead
                     95:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     96:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     97:   the equation model is restricted to two variables only (V2, V3)
                     98:   and the combination for V2 should be codtabm(k,1) instead of
                     99:   (codtabm(k,2), and the code should be
                    100:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    101:   made. All of these should be simplified once a day like we did in
                    102:   hpxij() for example by using precov[nres] which is computed in
                    103:   decoderesult for each nres of each resultline. Loop should be done
                    104:   on the equation model globally by distinguishing only product with
                    105:   age (which are changing with age) and no more on type of
                    106:   covariates, single dummies, single covariates.
                    107: 
1.332     brouard   108:   Revision 1.331  2022/08/07 05:40:09  brouard
                    109:   *** empty log message ***
                    110: 
1.331     brouard   111:   Revision 1.330  2022/08/06 07:18:25  brouard
                    112:   Summary: last 0.99r31
                    113: 
                    114:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    115: 
1.330     brouard   116:   Revision 1.329  2022/08/03 17:29:54  brouard
                    117:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    118: 
1.329     brouard   119:   Revision 1.328  2022/07/27 17:40:48  brouard
                    120:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    121: 
1.328     brouard   122:   Revision 1.327  2022/07/27 14:47:35  brouard
                    123:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    124: 
1.327     brouard   125:   Revision 1.326  2022/07/26 17:33:55  brouard
                    126:   Summary: some test with nres=1
                    127: 
1.326     brouard   128:   Revision 1.325  2022/07/25 14:27:23  brouard
                    129:   Summary: r30
                    130: 
                    131:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    132:   coredumped, revealed by Feiuno, thank you.
                    133: 
1.325     brouard   134:   Revision 1.324  2022/07/23 17:44:26  brouard
                    135:   *** empty log message ***
                    136: 
1.324     brouard   137:   Revision 1.323  2022/07/22 12:30:08  brouard
                    138:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    139: 
1.323     brouard   140:   Revision 1.322  2022/07/22 12:27:48  brouard
                    141:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    142: 
1.322     brouard   143:   Revision 1.321  2022/07/22 12:04:24  brouard
                    144:   Summary: r28
                    145: 
                    146:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    147: 
1.321     brouard   148:   Revision 1.320  2022/06/02 05:10:11  brouard
                    149:   *** empty log message ***
                    150: 
1.320     brouard   151:   Revision 1.319  2022/06/02 04:45:11  brouard
                    152:   * imach.c (Module): Adding the Wald tests from the log to the main
                    153:   htm for better display of the maximum likelihood estimators.
                    154: 
1.319     brouard   155:   Revision 1.318  2022/05/24 08:10:59  brouard
                    156:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    157:   of confidencce intervals with product in the equation modelC
                    158: 
1.318     brouard   159:   Revision 1.317  2022/05/15 15:06:23  brouard
                    160:   * imach.c (Module):  Some minor improvements
                    161: 
1.317     brouard   162:   Revision 1.316  2022/05/11 15:11:31  brouard
                    163:   Summary: r27
                    164: 
1.316     brouard   165:   Revision 1.315  2022/05/11 15:06:32  brouard
                    166:   *** empty log message ***
                    167: 
1.315     brouard   168:   Revision 1.314  2022/04/13 17:43:09  brouard
                    169:   * imach.c (Module): Adding link to text data files
                    170: 
1.314     brouard   171:   Revision 1.313  2022/04/11 15:57:42  brouard
                    172:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    173: 
1.313     brouard   174:   Revision 1.312  2022/04/05 21:24:39  brouard
                    175:   *** empty log message ***
                    176: 
1.312     brouard   177:   Revision 1.311  2022/04/05 21:03:51  brouard
                    178:   Summary: Fixed quantitative covariates
                    179: 
                    180:          Fixed covariates (dummy or quantitative)
                    181:        with missing values have never been allowed but are ERRORS and
                    182:        program quits. Standard deviations of fixed covariates were
                    183:        wrongly computed. Mean and standard deviations of time varying
                    184:        covariates are still not computed.
                    185: 
1.311     brouard   186:   Revision 1.310  2022/03/17 08:45:53  brouard
                    187:   Summary: 99r25
                    188: 
                    189:   Improving detection of errors: result lines should be compatible with
                    190:   the model.
                    191: 
1.310     brouard   192:   Revision 1.309  2021/05/20 12:39:14  brouard
                    193:   Summary: Version 0.99r24
                    194: 
1.309     brouard   195:   Revision 1.308  2021/03/31 13:11:57  brouard
                    196:   Summary: Version 0.99r23
                    197: 
                    198: 
                    199:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    200: 
1.308     brouard   201:   Revision 1.307  2021/03/08 18:11:32  brouard
                    202:   Summary: 0.99r22 fixed bug on result:
                    203: 
1.307     brouard   204:   Revision 1.306  2021/02/20 15:44:02  brouard
                    205:   Summary: Version 0.99r21
                    206: 
                    207:   * imach.c (Module): Fix bug on quitting after result lines!
                    208:   (Module): Version 0.99r21
                    209: 
1.306     brouard   210:   Revision 1.305  2021/02/20 15:28:30  brouard
                    211:   * imach.c (Module): Fix bug on quitting after result lines!
                    212: 
1.305     brouard   213:   Revision 1.304  2021/02/12 11:34:20  brouard
                    214:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    215: 
1.304     brouard   216:   Revision 1.303  2021/02/11 19:50:15  brouard
                    217:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    218: 
1.303     brouard   219:   Revision 1.302  2020/02/22 21:00:05  brouard
                    220:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    221:   and life table from the data without any state)
                    222: 
1.302     brouard   223:   Revision 1.301  2019/06/04 13:51:20  brouard
                    224:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    225: 
1.301     brouard   226:   Revision 1.300  2019/05/22 19:09:45  brouard
                    227:   Summary: version 0.99r19 of May 2019
                    228: 
1.300     brouard   229:   Revision 1.299  2019/05/22 18:37:08  brouard
                    230:   Summary: Cleaned 0.99r19
                    231: 
1.299     brouard   232:   Revision 1.298  2019/05/22 18:19:56  brouard
                    233:   *** empty log message ***
                    234: 
1.298     brouard   235:   Revision 1.297  2019/05/22 17:56:10  brouard
                    236:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    237: 
1.297     brouard   238:   Revision 1.296  2019/05/20 13:03:18  brouard
                    239:   Summary: Projection syntax simplified
                    240: 
                    241: 
                    242:   We can now start projections, forward or backward, from the mean date
                    243:   of inteviews up to or down to a number of years of projection:
                    244:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    245:   or
                    246:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    247:   or
                    248:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    249:   or
                    250:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    251: 
1.296     brouard   252:   Revision 1.295  2019/05/18 09:52:50  brouard
                    253:   Summary: doxygen tex bug
                    254: 
1.295     brouard   255:   Revision 1.294  2019/05/16 14:54:33  brouard
                    256:   Summary: There was some wrong lines added
                    257: 
1.294     brouard   258:   Revision 1.293  2019/05/09 15:17:34  brouard
                    259:   *** empty log message ***
                    260: 
1.293     brouard   261:   Revision 1.292  2019/05/09 14:17:20  brouard
                    262:   Summary: Some updates
                    263: 
1.292     brouard   264:   Revision 1.291  2019/05/09 13:44:18  brouard
                    265:   Summary: Before ncovmax
                    266: 
1.291     brouard   267:   Revision 1.290  2019/05/09 13:39:37  brouard
                    268:   Summary: 0.99r18 unlimited number of individuals
                    269: 
                    270:   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.
                    271: 
1.290     brouard   272:   Revision 1.289  2018/12/13 09:16:26  brouard
                    273:   Summary: Bug for young ages (<-30) will be in r17
                    274: 
1.289     brouard   275:   Revision 1.288  2018/05/02 20:58:27  brouard
                    276:   Summary: Some bugs fixed
                    277: 
1.288     brouard   278:   Revision 1.287  2018/05/01 17:57:25  brouard
                    279:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    280: 
1.287     brouard   281:   Revision 1.286  2018/04/27 14:27:04  brouard
                    282:   Summary: some minor bugs
                    283: 
1.286     brouard   284:   Revision 1.285  2018/04/21 21:02:16  brouard
                    285:   Summary: Some bugs fixed, valgrind tested
                    286: 
1.285     brouard   287:   Revision 1.284  2018/04/20 05:22:13  brouard
                    288:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    289: 
1.284     brouard   290:   Revision 1.283  2018/04/19 14:49:16  brouard
                    291:   Summary: Some minor bugs fixed
                    292: 
1.283     brouard   293:   Revision 1.282  2018/02/27 22:50:02  brouard
                    294:   *** empty log message ***
                    295: 
1.282     brouard   296:   Revision 1.281  2018/02/27 19:25:23  brouard
                    297:   Summary: Adding second argument for quitting
                    298: 
1.281     brouard   299:   Revision 1.280  2018/02/21 07:58:13  brouard
                    300:   Summary: 0.99r15
                    301: 
                    302:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    303: 
1.280     brouard   304:   Revision 1.279  2017/07/20 13:35:01  brouard
                    305:   Summary: temporary working
                    306: 
1.279     brouard   307:   Revision 1.278  2017/07/19 14:09:02  brouard
                    308:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    309: 
1.278     brouard   310:   Revision 1.277  2017/07/17 08:53:49  brouard
                    311:   Summary: BOM files can be read now
                    312: 
1.277     brouard   313:   Revision 1.276  2017/06/30 15:48:31  brouard
                    314:   Summary: Graphs improvements
                    315: 
1.276     brouard   316:   Revision 1.275  2017/06/30 13:39:33  brouard
                    317:   Summary: Saito's color
                    318: 
1.275     brouard   319:   Revision 1.274  2017/06/29 09:47:08  brouard
                    320:   Summary: Version 0.99r14
                    321: 
1.274     brouard   322:   Revision 1.273  2017/06/27 11:06:02  brouard
                    323:   Summary: More documentation on projections
                    324: 
1.273     brouard   325:   Revision 1.272  2017/06/27 10:22:40  brouard
                    326:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    327: 
1.272     brouard   328:   Revision 1.271  2017/06/27 10:17:50  brouard
                    329:   Summary: Some bug with rint
                    330: 
1.271     brouard   331:   Revision 1.270  2017/05/24 05:45:29  brouard
                    332:   *** empty log message ***
                    333: 
1.270     brouard   334:   Revision 1.269  2017/05/23 08:39:25  brouard
                    335:   Summary: Code into subroutine, cleanings
                    336: 
1.269     brouard   337:   Revision 1.268  2017/05/18 20:09:32  brouard
                    338:   Summary: backprojection and confidence intervals of backprevalence
                    339: 
1.268     brouard   340:   Revision 1.267  2017/05/13 10:25:05  brouard
                    341:   Summary: temporary save for backprojection
                    342: 
1.267     brouard   343:   Revision 1.266  2017/05/13 07:26:12  brouard
                    344:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    345: 
1.266     brouard   346:   Revision 1.265  2017/04/26 16:22:11  brouard
                    347:   Summary: imach 0.99r13 Some bugs fixed
                    348: 
1.265     brouard   349:   Revision 1.264  2017/04/26 06:01:29  brouard
                    350:   Summary: Labels in graphs
                    351: 
1.264     brouard   352:   Revision 1.263  2017/04/24 15:23:15  brouard
                    353:   Summary: to save
                    354: 
1.263     brouard   355:   Revision 1.262  2017/04/18 16:48:12  brouard
                    356:   *** empty log message ***
                    357: 
1.262     brouard   358:   Revision 1.261  2017/04/05 10:14:09  brouard
                    359:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    360: 
1.261     brouard   361:   Revision 1.260  2017/04/04 17:46:59  brouard
                    362:   Summary: Gnuplot indexations fixed (humm)
                    363: 
1.260     brouard   364:   Revision 1.259  2017/04/04 13:01:16  brouard
                    365:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    366: 
1.259     brouard   367:   Revision 1.258  2017/04/03 10:17:47  brouard
                    368:   Summary: Version 0.99r12
                    369: 
                    370:   Some cleanings, conformed with updated documentation.
                    371: 
1.258     brouard   372:   Revision 1.257  2017/03/29 16:53:30  brouard
                    373:   Summary: Temp
                    374: 
1.257     brouard   375:   Revision 1.256  2017/03/27 05:50:23  brouard
                    376:   Summary: Temporary
                    377: 
1.256     brouard   378:   Revision 1.255  2017/03/08 16:02:28  brouard
                    379:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    380: 
1.255     brouard   381:   Revision 1.254  2017/03/08 07:13:00  brouard
                    382:   Summary: Fixing data parameter line
                    383: 
1.254     brouard   384:   Revision 1.253  2016/12/15 11:59:41  brouard
                    385:   Summary: 0.99 in progress
                    386: 
1.253     brouard   387:   Revision 1.252  2016/09/15 21:15:37  brouard
                    388:   *** empty log message ***
                    389: 
1.252     brouard   390:   Revision 1.251  2016/09/15 15:01:13  brouard
                    391:   Summary: not working
                    392: 
1.251     brouard   393:   Revision 1.250  2016/09/08 16:07:27  brouard
                    394:   Summary: continue
                    395: 
1.250     brouard   396:   Revision 1.249  2016/09/07 17:14:18  brouard
                    397:   Summary: Starting values from frequencies
                    398: 
1.249     brouard   399:   Revision 1.248  2016/09/07 14:10:18  brouard
                    400:   *** empty log message ***
                    401: 
1.248     brouard   402:   Revision 1.247  2016/09/02 11:11:21  brouard
                    403:   *** empty log message ***
                    404: 
1.247     brouard   405:   Revision 1.246  2016/09/02 08:49:22  brouard
                    406:   *** empty log message ***
                    407: 
1.246     brouard   408:   Revision 1.245  2016/09/02 07:25:01  brouard
                    409:   *** empty log message ***
                    410: 
1.245     brouard   411:   Revision 1.244  2016/09/02 07:17:34  brouard
                    412:   *** empty log message ***
                    413: 
1.244     brouard   414:   Revision 1.243  2016/09/02 06:45:35  brouard
                    415:   *** empty log message ***
                    416: 
1.243     brouard   417:   Revision 1.242  2016/08/30 15:01:20  brouard
                    418:   Summary: Fixing a lots
                    419: 
1.242     brouard   420:   Revision 1.241  2016/08/29 17:17:25  brouard
                    421:   Summary: gnuplot problem in Back projection to fix
                    422: 
1.241     brouard   423:   Revision 1.240  2016/08/29 07:53:18  brouard
                    424:   Summary: Better
                    425: 
1.240     brouard   426:   Revision 1.239  2016/08/26 15:51:03  brouard
                    427:   Summary: Improvement in Powell output in order to copy and paste
                    428: 
                    429:   Author:
                    430: 
1.239     brouard   431:   Revision 1.238  2016/08/26 14:23:35  brouard
                    432:   Summary: Starting tests of 0.99
                    433: 
1.238     brouard   434:   Revision 1.237  2016/08/26 09:20:19  brouard
                    435:   Summary: to valgrind
                    436: 
1.237     brouard   437:   Revision 1.236  2016/08/25 10:50:18  brouard
                    438:   *** empty log message ***
                    439: 
1.236     brouard   440:   Revision 1.235  2016/08/25 06:59:23  brouard
                    441:   *** empty log message ***
                    442: 
1.235     brouard   443:   Revision 1.234  2016/08/23 16:51:20  brouard
                    444:   *** empty log message ***
                    445: 
1.234     brouard   446:   Revision 1.233  2016/08/23 07:40:50  brouard
                    447:   Summary: not working
                    448: 
1.233     brouard   449:   Revision 1.232  2016/08/22 14:20:21  brouard
                    450:   Summary: not working
                    451: 
1.232     brouard   452:   Revision 1.231  2016/08/22 07:17:15  brouard
                    453:   Summary: not working
                    454: 
1.231     brouard   455:   Revision 1.230  2016/08/22 06:55:53  brouard
                    456:   Summary: Not working
                    457: 
1.230     brouard   458:   Revision 1.229  2016/07/23 09:45:53  brouard
                    459:   Summary: Completing for func too
                    460: 
1.229     brouard   461:   Revision 1.228  2016/07/22 17:45:30  brouard
                    462:   Summary: Fixing some arrays, still debugging
                    463: 
1.227     brouard   464:   Revision 1.226  2016/07/12 18:42:34  brouard
                    465:   Summary: temp
                    466: 
1.226     brouard   467:   Revision 1.225  2016/07/12 08:40:03  brouard
                    468:   Summary: saving but not running
                    469: 
1.225     brouard   470:   Revision 1.224  2016/07/01 13:16:01  brouard
                    471:   Summary: Fixes
                    472: 
1.224     brouard   473:   Revision 1.223  2016/02/19 09:23:35  brouard
                    474:   Summary: temporary
                    475: 
1.223     brouard   476:   Revision 1.222  2016/02/17 08:14:50  brouard
                    477:   Summary: Probably last 0.98 stable version 0.98r6
                    478: 
1.222     brouard   479:   Revision 1.221  2016/02/15 23:35:36  brouard
                    480:   Summary: minor bug
                    481: 
1.220     brouard   482:   Revision 1.219  2016/02/15 00:48:12  brouard
                    483:   *** empty log message ***
                    484: 
1.219     brouard   485:   Revision 1.218  2016/02/12 11:29:23  brouard
                    486:   Summary: 0.99 Back projections
                    487: 
1.218     brouard   488:   Revision 1.217  2015/12/23 17:18:31  brouard
                    489:   Summary: Experimental backcast
                    490: 
1.217     brouard   491:   Revision 1.216  2015/12/18 17:32:11  brouard
                    492:   Summary: 0.98r4 Warning and status=-2
                    493: 
                    494:   Version 0.98r4 is now:
                    495:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    496:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    497:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    498: 
1.216     brouard   499:   Revision 1.215  2015/12/16 08:52:24  brouard
                    500:   Summary: 0.98r4 working
                    501: 
1.215     brouard   502:   Revision 1.214  2015/12/16 06:57:54  brouard
                    503:   Summary: temporary not working
                    504: 
1.214     brouard   505:   Revision 1.213  2015/12/11 18:22:17  brouard
                    506:   Summary: 0.98r4
                    507: 
1.213     brouard   508:   Revision 1.212  2015/11/21 12:47:24  brouard
                    509:   Summary: minor typo
                    510: 
1.212     brouard   511:   Revision 1.211  2015/11/21 12:41:11  brouard
                    512:   Summary: 0.98r3 with some graph of projected cross-sectional
                    513: 
                    514:   Author: Nicolas Brouard
                    515: 
1.211     brouard   516:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   517:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   518:   Summary: Adding ftolpl parameter
                    519:   Author: N Brouard
                    520: 
                    521:   We had difficulties to get smoothed confidence intervals. It was due
                    522:   to the period prevalence which wasn't computed accurately. The inner
                    523:   parameter ftolpl is now an outer parameter of the .imach parameter
                    524:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    525:   computation are long.
                    526: 
1.209     brouard   527:   Revision 1.208  2015/11/17 14:31:57  brouard
                    528:   Summary: temporary
                    529: 
1.208     brouard   530:   Revision 1.207  2015/10/27 17:36:57  brouard
                    531:   *** empty log message ***
                    532: 
1.207     brouard   533:   Revision 1.206  2015/10/24 07:14:11  brouard
                    534:   *** empty log message ***
                    535: 
1.206     brouard   536:   Revision 1.205  2015/10/23 15:50:53  brouard
                    537:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    538: 
1.205     brouard   539:   Revision 1.204  2015/10/01 16:20:26  brouard
                    540:   Summary: Some new graphs of contribution to likelihood
                    541: 
1.204     brouard   542:   Revision 1.203  2015/09/30 17:45:14  brouard
                    543:   Summary: looking at better estimation of the hessian
                    544: 
                    545:   Also a better criteria for convergence to the period prevalence And
                    546:   therefore adding the number of years needed to converge. (The
                    547:   prevalence in any alive state shold sum to one
                    548: 
1.203     brouard   549:   Revision 1.202  2015/09/22 19:45:16  brouard
                    550:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    551: 
1.202     brouard   552:   Revision 1.201  2015/09/15 17:34:58  brouard
                    553:   Summary: 0.98r0
                    554: 
                    555:   - Some new graphs like suvival functions
                    556:   - Some bugs fixed like model=1+age+V2.
                    557: 
1.201     brouard   558:   Revision 1.200  2015/09/09 16:53:55  brouard
                    559:   Summary: Big bug thanks to Flavia
                    560: 
                    561:   Even model=1+age+V2. did not work anymore
                    562: 
1.200     brouard   563:   Revision 1.199  2015/09/07 14:09:23  brouard
                    564:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    565: 
1.199     brouard   566:   Revision 1.198  2015/09/03 07:14:39  brouard
                    567:   Summary: 0.98q5 Flavia
                    568: 
1.198     brouard   569:   Revision 1.197  2015/09/01 18:24:39  brouard
                    570:   *** empty log message ***
                    571: 
1.197     brouard   572:   Revision 1.196  2015/08/18 23:17:52  brouard
                    573:   Summary: 0.98q5
                    574: 
1.196     brouard   575:   Revision 1.195  2015/08/18 16:28:39  brouard
                    576:   Summary: Adding a hack for testing purpose
                    577: 
                    578:   After reading the title, ftol and model lines, if the comment line has
                    579:   a q, starting with #q, the answer at the end of the run is quit. It
                    580:   permits to run test files in batch with ctest. The former workaround was
                    581:   $ echo q | imach foo.imach
                    582: 
1.195     brouard   583:   Revision 1.194  2015/08/18 13:32:00  brouard
                    584:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    585: 
1.194     brouard   586:   Revision 1.193  2015/08/04 07:17:42  brouard
                    587:   Summary: 0.98q4
                    588: 
1.193     brouard   589:   Revision 1.192  2015/07/16 16:49:02  brouard
                    590:   Summary: Fixing some outputs
                    591: 
1.192     brouard   592:   Revision 1.191  2015/07/14 10:00:33  brouard
                    593:   Summary: Some fixes
                    594: 
1.191     brouard   595:   Revision 1.190  2015/05/05 08:51:13  brouard
                    596:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    597: 
                    598:   Fix 1+age+.
                    599: 
1.190     brouard   600:   Revision 1.189  2015/04/30 14:45:16  brouard
                    601:   Summary: 0.98q2
                    602: 
1.189     brouard   603:   Revision 1.188  2015/04/30 08:27:53  brouard
                    604:   *** empty log message ***
                    605: 
1.188     brouard   606:   Revision 1.187  2015/04/29 09:11:15  brouard
                    607:   *** empty log message ***
                    608: 
1.187     brouard   609:   Revision 1.186  2015/04/23 12:01:52  brouard
                    610:   Summary: V1*age is working now, version 0.98q1
                    611: 
                    612:   Some codes had been disabled in order to simplify and Vn*age was
                    613:   working in the optimization phase, ie, giving correct MLE parameters,
                    614:   but, as usual, outputs were not correct and program core dumped.
                    615: 
1.186     brouard   616:   Revision 1.185  2015/03/11 13:26:42  brouard
                    617:   Summary: Inclusion of compile and links command line for Intel Compiler
                    618: 
1.185     brouard   619:   Revision 1.184  2015/03/11 11:52:39  brouard
                    620:   Summary: Back from Windows 8. Intel Compiler
                    621: 
1.184     brouard   622:   Revision 1.183  2015/03/10 20:34:32  brouard
                    623:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    624: 
                    625:   We use directest instead of original Powell test; probably no
                    626:   incidence on the results, but better justifications;
                    627:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    628:   wrong results.
                    629: 
1.183     brouard   630:   Revision 1.182  2015/02/12 08:19:57  brouard
                    631:   Summary: Trying to keep directest which seems simpler and more general
                    632:   Author: Nicolas Brouard
                    633: 
1.182     brouard   634:   Revision 1.181  2015/02/11 23:22:24  brouard
                    635:   Summary: Comments on Powell added
                    636: 
                    637:   Author:
                    638: 
1.181     brouard   639:   Revision 1.180  2015/02/11 17:33:45  brouard
                    640:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    641: 
1.180     brouard   642:   Revision 1.179  2015/01/04 09:57:06  brouard
                    643:   Summary: back to OS/X
                    644: 
1.179     brouard   645:   Revision 1.178  2015/01/04 09:35:48  brouard
                    646:   *** empty log message ***
                    647: 
1.178     brouard   648:   Revision 1.177  2015/01/03 18:40:56  brouard
                    649:   Summary: Still testing ilc32 on OSX
                    650: 
1.177     brouard   651:   Revision 1.176  2015/01/03 16:45:04  brouard
                    652:   *** empty log message ***
                    653: 
1.176     brouard   654:   Revision 1.175  2015/01/03 16:33:42  brouard
                    655:   *** empty log message ***
                    656: 
1.175     brouard   657:   Revision 1.174  2015/01/03 16:15:49  brouard
                    658:   Summary: Still in cross-compilation
                    659: 
1.174     brouard   660:   Revision 1.173  2015/01/03 12:06:26  brouard
                    661:   Summary: trying to detect cross-compilation
                    662: 
1.173     brouard   663:   Revision 1.172  2014/12/27 12:07:47  brouard
                    664:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    665: 
1.172     brouard   666:   Revision 1.171  2014/12/23 13:26:59  brouard
                    667:   Summary: Back from Visual C
                    668: 
                    669:   Still problem with utsname.h on Windows
                    670: 
1.171     brouard   671:   Revision 1.170  2014/12/23 11:17:12  brouard
                    672:   Summary: Cleaning some \%% back to %%
                    673: 
                    674:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    675: 
1.170     brouard   676:   Revision 1.169  2014/12/22 23:08:31  brouard
                    677:   Summary: 0.98p
                    678: 
                    679:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    680: 
1.169     brouard   681:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   682:   Summary: update
1.169     brouard   683: 
1.168     brouard   684:   Revision 1.167  2014/12/22 13:50:56  brouard
                    685:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    686: 
                    687:   Testing on Linux 64
                    688: 
1.167     brouard   689:   Revision 1.166  2014/12/22 11:40:47  brouard
                    690:   *** empty log message ***
                    691: 
1.166     brouard   692:   Revision 1.165  2014/12/16 11:20:36  brouard
                    693:   Summary: After compiling on Visual C
                    694: 
                    695:   * imach.c (Module): Merging 1.61 to 1.162
                    696: 
1.165     brouard   697:   Revision 1.164  2014/12/16 10:52:11  brouard
                    698:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    699: 
                    700:   * imach.c (Module): Merging 1.61 to 1.162
                    701: 
1.164     brouard   702:   Revision 1.163  2014/12/16 10:30:11  brouard
                    703:   * imach.c (Module): Merging 1.61 to 1.162
                    704: 
1.163     brouard   705:   Revision 1.162  2014/09/25 11:43:39  brouard
                    706:   Summary: temporary backup 0.99!
                    707: 
1.162     brouard   708:   Revision 1.1  2014/09/16 11:06:58  brouard
                    709:   Summary: With some code (wrong) for nlopt
                    710: 
                    711:   Author:
                    712: 
                    713:   Revision 1.161  2014/09/15 20:41:41  brouard
                    714:   Summary: Problem with macro SQR on Intel compiler
                    715: 
1.161     brouard   716:   Revision 1.160  2014/09/02 09:24:05  brouard
                    717:   *** empty log message ***
                    718: 
1.160     brouard   719:   Revision 1.159  2014/09/01 10:34:10  brouard
                    720:   Summary: WIN32
                    721:   Author: Brouard
                    722: 
1.159     brouard   723:   Revision 1.158  2014/08/27 17:11:51  brouard
                    724:   *** empty log message ***
                    725: 
1.158     brouard   726:   Revision 1.157  2014/08/27 16:26:55  brouard
                    727:   Summary: Preparing windows Visual studio version
                    728:   Author: Brouard
                    729: 
                    730:   In order to compile on Visual studio, time.h is now correct and time_t
                    731:   and tm struct should be used. difftime should be used but sometimes I
                    732:   just make the differences in raw time format (time(&now).
                    733:   Trying to suppress #ifdef LINUX
                    734:   Add xdg-open for __linux in order to open default browser.
                    735: 
1.157     brouard   736:   Revision 1.156  2014/08/25 20:10:10  brouard
                    737:   *** empty log message ***
                    738: 
1.156     brouard   739:   Revision 1.155  2014/08/25 18:32:34  brouard
                    740:   Summary: New compile, minor changes
                    741:   Author: Brouard
                    742: 
1.155     brouard   743:   Revision 1.154  2014/06/20 17:32:08  brouard
                    744:   Summary: Outputs now all graphs of convergence to period prevalence
                    745: 
1.154     brouard   746:   Revision 1.153  2014/06/20 16:45:46  brouard
                    747:   Summary: If 3 live state, convergence to period prevalence on same graph
                    748:   Author: Brouard
                    749: 
1.153     brouard   750:   Revision 1.152  2014/06/18 17:54:09  brouard
                    751:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    752: 
1.152     brouard   753:   Revision 1.151  2014/06/18 16:43:30  brouard
                    754:   *** empty log message ***
                    755: 
1.151     brouard   756:   Revision 1.150  2014/06/18 16:42:35  brouard
                    757:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    758:   Author: brouard
                    759: 
1.150     brouard   760:   Revision 1.149  2014/06/18 15:51:14  brouard
                    761:   Summary: Some fixes in parameter files errors
                    762:   Author: Nicolas Brouard
                    763: 
1.149     brouard   764:   Revision 1.148  2014/06/17 17:38:48  brouard
                    765:   Summary: Nothing new
                    766:   Author: Brouard
                    767: 
                    768:   Just a new packaging for OS/X version 0.98nS
                    769: 
1.148     brouard   770:   Revision 1.147  2014/06/16 10:33:11  brouard
                    771:   *** empty log message ***
                    772: 
1.147     brouard   773:   Revision 1.146  2014/06/16 10:20:28  brouard
                    774:   Summary: Merge
                    775:   Author: Brouard
                    776: 
                    777:   Merge, before building revised version.
                    778: 
1.146     brouard   779:   Revision 1.145  2014/06/10 21:23:15  brouard
                    780:   Summary: Debugging with valgrind
                    781:   Author: Nicolas Brouard
                    782: 
                    783:   Lot of changes in order to output the results with some covariates
                    784:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    785:   improve the code.
                    786:   No more memory valgrind error but a lot has to be done in order to
                    787:   continue the work of splitting the code into subroutines.
                    788:   Also, decodemodel has been improved. Tricode is still not
                    789:   optimal. nbcode should be improved. Documentation has been added in
                    790:   the source code.
                    791: 
1.144     brouard   792:   Revision 1.143  2014/01/26 09:45:38  brouard
                    793:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    794: 
                    795:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    796:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    797: 
1.143     brouard   798:   Revision 1.142  2014/01/26 03:57:36  brouard
                    799:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    800: 
                    801:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    802: 
1.142     brouard   803:   Revision 1.141  2014/01/26 02:42:01  brouard
                    804:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    805: 
1.141     brouard   806:   Revision 1.140  2011/09/02 10:37:54  brouard
                    807:   Summary: times.h is ok with mingw32 now.
                    808: 
1.140     brouard   809:   Revision 1.139  2010/06/14 07:50:17  brouard
                    810:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    811:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    812: 
1.139     brouard   813:   Revision 1.138  2010/04/30 18:19:40  brouard
                    814:   *** empty log message ***
                    815: 
1.138     brouard   816:   Revision 1.137  2010/04/29 18:11:38  brouard
                    817:   (Module): Checking covariates for more complex models
                    818:   than V1+V2. A lot of change to be done. Unstable.
                    819: 
1.137     brouard   820:   Revision 1.136  2010/04/26 20:30:53  brouard
                    821:   (Module): merging some libgsl code. Fixing computation
                    822:   of likelione (using inter/intrapolation if mle = 0) in order to
                    823:   get same likelihood as if mle=1.
                    824:   Some cleaning of code and comments added.
                    825: 
1.136     brouard   826:   Revision 1.135  2009/10/29 15:33:14  brouard
                    827:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    828: 
1.135     brouard   829:   Revision 1.134  2009/10/29 13:18:53  brouard
                    830:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    831: 
1.134     brouard   832:   Revision 1.133  2009/07/06 10:21:25  brouard
                    833:   just nforces
                    834: 
1.133     brouard   835:   Revision 1.132  2009/07/06 08:22:05  brouard
                    836:   Many tings
                    837: 
1.132     brouard   838:   Revision 1.131  2009/06/20 16:22:47  brouard
                    839:   Some dimensions resccaled
                    840: 
1.131     brouard   841:   Revision 1.130  2009/05/26 06:44:34  brouard
                    842:   (Module): Max Covariate is now set to 20 instead of 8. A
                    843:   lot of cleaning with variables initialized to 0. Trying to make
                    844:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    845: 
1.130     brouard   846:   Revision 1.129  2007/08/31 13:49:27  lievre
                    847:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    848: 
1.129     lievre    849:   Revision 1.128  2006/06/30 13:02:05  brouard
                    850:   (Module): Clarifications on computing e.j
                    851: 
1.128     brouard   852:   Revision 1.127  2006/04/28 18:11:50  brouard
                    853:   (Module): Yes the sum of survivors was wrong since
                    854:   imach-114 because nhstepm was no more computed in the age
                    855:   loop. Now we define nhstepma in the age loop.
                    856:   (Module): In order to speed up (in case of numerous covariates) we
                    857:   compute health expectancies (without variances) in a first step
                    858:   and then all the health expectancies with variances or standard
                    859:   deviation (needs data from the Hessian matrices) which slows the
                    860:   computation.
                    861:   In the future we should be able to stop the program is only health
                    862:   expectancies and graph are needed without standard deviations.
                    863: 
1.127     brouard   864:   Revision 1.126  2006/04/28 17:23:28  brouard
                    865:   (Module): Yes the sum of survivors was wrong since
                    866:   imach-114 because nhstepm was no more computed in the age
                    867:   loop. Now we define nhstepma in the age loop.
                    868:   Version 0.98h
                    869: 
1.126     brouard   870:   Revision 1.125  2006/04/04 15:20:31  lievre
                    871:   Errors in calculation of health expectancies. Age was not initialized.
                    872:   Forecasting file added.
                    873: 
                    874:   Revision 1.124  2006/03/22 17:13:53  lievre
                    875:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    876:   The log-likelihood is printed in the log file
                    877: 
                    878:   Revision 1.123  2006/03/20 10:52:43  brouard
                    879:   * imach.c (Module): <title> changed, corresponds to .htm file
                    880:   name. <head> headers where missing.
                    881: 
                    882:   * imach.c (Module): Weights can have a decimal point as for
                    883:   English (a comma might work with a correct LC_NUMERIC environment,
                    884:   otherwise the weight is truncated).
                    885:   Modification of warning when the covariates values are not 0 or
                    886:   1.
                    887:   Version 0.98g
                    888: 
                    889:   Revision 1.122  2006/03/20 09:45:41  brouard
                    890:   (Module): Weights can have a decimal point as for
                    891:   English (a comma might work with a correct LC_NUMERIC environment,
                    892:   otherwise the weight is truncated).
                    893:   Modification of warning when the covariates values are not 0 or
                    894:   1.
                    895:   Version 0.98g
                    896: 
                    897:   Revision 1.121  2006/03/16 17:45:01  lievre
                    898:   * imach.c (Module): Comments concerning covariates added
                    899: 
                    900:   * imach.c (Module): refinements in the computation of lli if
                    901:   status=-2 in order to have more reliable computation if stepm is
                    902:   not 1 month. Version 0.98f
                    903: 
                    904:   Revision 1.120  2006/03/16 15:10:38  lievre
                    905:   (Module): refinements in the computation of lli if
                    906:   status=-2 in order to have more reliable computation if stepm is
                    907:   not 1 month. Version 0.98f
                    908: 
                    909:   Revision 1.119  2006/03/15 17:42:26  brouard
                    910:   (Module): Bug if status = -2, the loglikelihood was
                    911:   computed as likelihood omitting the logarithm. Version O.98e
                    912: 
                    913:   Revision 1.118  2006/03/14 18:20:07  brouard
                    914:   (Module): varevsij Comments added explaining the second
                    915:   table of variances if popbased=1 .
                    916:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    917:   (Module): Function pstamp added
                    918:   (Module): Version 0.98d
                    919: 
                    920:   Revision 1.117  2006/03/14 17:16:22  brouard
                    921:   (Module): varevsij Comments added explaining the second
                    922:   table of variances if popbased=1 .
                    923:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    924:   (Module): Function pstamp added
                    925:   (Module): Version 0.98d
                    926: 
                    927:   Revision 1.116  2006/03/06 10:29:27  brouard
                    928:   (Module): Variance-covariance wrong links and
                    929:   varian-covariance of ej. is needed (Saito).
                    930: 
                    931:   Revision 1.115  2006/02/27 12:17:45  brouard
                    932:   (Module): One freematrix added in mlikeli! 0.98c
                    933: 
                    934:   Revision 1.114  2006/02/26 12:57:58  brouard
                    935:   (Module): Some improvements in processing parameter
                    936:   filename with strsep.
                    937: 
                    938:   Revision 1.113  2006/02/24 14:20:24  brouard
                    939:   (Module): Memory leaks checks with valgrind and:
                    940:   datafile was not closed, some imatrix were not freed and on matrix
                    941:   allocation too.
                    942: 
                    943:   Revision 1.112  2006/01/30 09:55:26  brouard
                    944:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    945: 
                    946:   Revision 1.111  2006/01/25 20:38:18  brouard
                    947:   (Module): Lots of cleaning and bugs added (Gompertz)
                    948:   (Module): Comments can be added in data file. Missing date values
                    949:   can be a simple dot '.'.
                    950: 
                    951:   Revision 1.110  2006/01/25 00:51:50  brouard
                    952:   (Module): Lots of cleaning and bugs added (Gompertz)
                    953: 
                    954:   Revision 1.109  2006/01/24 19:37:15  brouard
                    955:   (Module): Comments (lines starting with a #) are allowed in data.
                    956: 
                    957:   Revision 1.108  2006/01/19 18:05:42  lievre
                    958:   Gnuplot problem appeared...
                    959:   To be fixed
                    960: 
                    961:   Revision 1.107  2006/01/19 16:20:37  brouard
                    962:   Test existence of gnuplot in imach path
                    963: 
                    964:   Revision 1.106  2006/01/19 13:24:36  brouard
                    965:   Some cleaning and links added in html output
                    966: 
                    967:   Revision 1.105  2006/01/05 20:23:19  lievre
                    968:   *** empty log message ***
                    969: 
                    970:   Revision 1.104  2005/09/30 16:11:43  lievre
                    971:   (Module): sump fixed, loop imx fixed, and simplifications.
                    972:   (Module): If the status is missing at the last wave but we know
                    973:   that the person is alive, then we can code his/her status as -2
                    974:   (instead of missing=-1 in earlier versions) and his/her
                    975:   contributions to the likelihood is 1 - Prob of dying from last
                    976:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    977:   the healthy state at last known wave). Version is 0.98
                    978: 
                    979:   Revision 1.103  2005/09/30 15:54:49  lievre
                    980:   (Module): sump fixed, loop imx fixed, and simplifications.
                    981: 
                    982:   Revision 1.102  2004/09/15 17:31:30  brouard
                    983:   Add the possibility to read data file including tab characters.
                    984: 
                    985:   Revision 1.101  2004/09/15 10:38:38  brouard
                    986:   Fix on curr_time
                    987: 
                    988:   Revision 1.100  2004/07/12 18:29:06  brouard
                    989:   Add version for Mac OS X. Just define UNIX in Makefile
                    990: 
                    991:   Revision 1.99  2004/06/05 08:57:40  brouard
                    992:   *** empty log message ***
                    993: 
                    994:   Revision 1.98  2004/05/16 15:05:56  brouard
                    995:   New version 0.97 . First attempt to estimate force of mortality
                    996:   directly from the data i.e. without the need of knowing the health
                    997:   state at each age, but using a Gompertz model: log u =a + b*age .
                    998:   This is the basic analysis of mortality and should be done before any
                    999:   other analysis, in order to test if the mortality estimated from the
                   1000:   cross-longitudinal survey is different from the mortality estimated
                   1001:   from other sources like vital statistic data.
                   1002: 
                   1003:   The same imach parameter file can be used but the option for mle should be -3.
                   1004: 
1.324     brouard  1005:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1006:   former routines in order to include the new code within the former code.
                   1007: 
                   1008:   The output is very simple: only an estimate of the intercept and of
                   1009:   the slope with 95% confident intervals.
                   1010: 
                   1011:   Current limitations:
                   1012:   A) Even if you enter covariates, i.e. with the
                   1013:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1014:   B) There is no computation of Life Expectancy nor Life Table.
                   1015: 
                   1016:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1017:   Version 0.96d. Population forecasting command line is (temporarily)
                   1018:   suppressed.
                   1019: 
                   1020:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1021:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1022:   rewritten within the same printf. Workaround: many printfs.
                   1023: 
                   1024:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1025:   * imach.c (Repository):
                   1026:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1027:   matrix (cov(a12,c31) instead of numbers.
                   1028: 
                   1029:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1030:   Just cleaning
                   1031: 
                   1032:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1033:   (Module): On windows (cygwin) function asctime_r doesn't
                   1034:   exist so I changed back to asctime which exists.
                   1035:   (Module): Version 0.96b
                   1036: 
                   1037:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1038:   (Module): On windows (cygwin) function asctime_r doesn't
                   1039:   exist so I changed back to asctime which exists.
                   1040: 
                   1041:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1042:   * imach.c (Repository): Duplicated warning errors corrected.
                   1043:   (Repository): Elapsed time after each iteration is now output. It
                   1044:   helps to forecast when convergence will be reached. Elapsed time
                   1045:   is stamped in powell.  We created a new html file for the graphs
                   1046:   concerning matrix of covariance. It has extension -cov.htm.
                   1047: 
                   1048:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1049:   (Module): Some bugs corrected for windows. Also, when
                   1050:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1051:   of the covariance matrix to be input.
                   1052: 
                   1053:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1054:   (Module): Some bugs corrected for windows. Also, when
                   1055:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1056:   of the covariance matrix to be input.
                   1057: 
                   1058:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1059:   * 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.
                   1060: 
                   1061:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1062:   Version 0.96
                   1063: 
                   1064:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1065:   (Module): Change position of html and gnuplot routines and added
                   1066:   routine fileappend.
                   1067: 
                   1068:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1069:   * imach.c (Repository): Check when date of death was earlier that
                   1070:   current date of interview. It may happen when the death was just
                   1071:   prior to the death. In this case, dh was negative and likelihood
                   1072:   was wrong (infinity). We still send an "Error" but patch by
                   1073:   assuming that the date of death was just one stepm after the
                   1074:   interview.
                   1075:   (Repository): Because some people have very long ID (first column)
                   1076:   we changed int to long in num[] and we added a new lvector for
                   1077:   memory allocation. But we also truncated to 8 characters (left
                   1078:   truncation)
                   1079:   (Repository): No more line truncation errors.
                   1080: 
                   1081:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1082:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1083:   place. It differs from routine "prevalence" which may be called
                   1084:   many times. Probs is memory consuming and must be used with
                   1085:   parcimony.
                   1086:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1087: 
                   1088:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1089:   *** empty log message ***
                   1090: 
                   1091:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1092:   Add log in  imach.c and  fullversion number is now printed.
                   1093: 
                   1094: */
                   1095: /*
                   1096:    Interpolated Markov Chain
                   1097: 
                   1098:   Short summary of the programme:
                   1099:   
1.227     brouard  1100:   This program computes Healthy Life Expectancies or State-specific
                   1101:   (if states aren't health statuses) Expectancies from
                   1102:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1103: 
                   1104:   -1- a first survey ("cross") where individuals from different ages
                   1105:   are interviewed on their health status or degree of disability (in
                   1106:   the case of a health survey which is our main interest)
                   1107: 
                   1108:   -2- at least a second wave of interviews ("longitudinal") which
                   1109:   measure each change (if any) in individual health status.  Health
                   1110:   expectancies are computed from the time spent in each health state
                   1111:   according to a model. More health states you consider, more time is
                   1112:   necessary to reach the Maximum Likelihood of the parameters involved
                   1113:   in the model.  The simplest model is the multinomial logistic model
                   1114:   where pij is the probability to be observed in state j at the second
                   1115:   wave conditional to be observed in state i at the first
                   1116:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1117:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1118:   have a more complex model than "constant and age", you should modify
                   1119:   the program where the markup *Covariates have to be included here
                   1120:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1121:   convergence.
                   1122: 
                   1123:   The advantage of this computer programme, compared to a simple
                   1124:   multinomial logistic model, is clear when the delay between waves is not
                   1125:   identical for each individual. Also, if a individual missed an
                   1126:   intermediate interview, the information is lost, but taken into
                   1127:   account using an interpolation or extrapolation.  
                   1128: 
                   1129:   hPijx is the probability to be observed in state i at age x+h
                   1130:   conditional to the observed state i at age x. The delay 'h' can be
                   1131:   split into an exact number (nh*stepm) of unobserved intermediate
                   1132:   states. This elementary transition (by month, quarter,
                   1133:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1134:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1135:   and the contribution of each individual to the likelihood is simply
                   1136:   hPijx.
                   1137: 
                   1138:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1139:   of the life expectancies. It also computes the period (stable) prevalence.
                   1140: 
                   1141: Back prevalence and projections:
1.227     brouard  1142: 
                   1143:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1144:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1145:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1146:    mobilavproj)
                   1147: 
                   1148:     Computes the back prevalence limit for any combination of
                   1149:     covariate values k at any age between ageminpar and agemaxpar and
                   1150:     returns it in **bprlim. In the loops,
                   1151: 
                   1152:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1153:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1154: 
                   1155:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1156:    Computes for any combination of covariates k and any age between bage and fage 
                   1157:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1158:                        oldm=oldms;savm=savms;
1.227     brouard  1159: 
1.267     brouard  1160:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1161:      Computes the transition matrix starting at age 'age' over
                   1162:      'nhstepm*hstepm*stepm' months (i.e. until
                   1163:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1164:      nhstepm*hstepm matrices. 
                   1165: 
                   1166:      Returns p3mat[i][j][h] after calling
                   1167:      p3mat[i][j][h]=matprod2(newm,
                   1168:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1169:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1170:      oldm);
1.226     brouard  1171: 
                   1172: Important routines
                   1173: 
                   1174: - func (or funcone), computes logit (pij) distinguishing
                   1175:   o fixed variables (single or product dummies or quantitative);
                   1176:   o varying variables by:
                   1177:    (1) wave (single, product dummies, quantitative), 
                   1178:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1179:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1180:        % varying dummy (not done) or quantitative (not done);
                   1181: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1182:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1183: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1184:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1185:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1186: 
1.226     brouard  1187: 
                   1188:   
1.324     brouard  1189:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1190:            Institut national d'études démographiques, Paris.
1.126     brouard  1191:   This software have been partly granted by Euro-REVES, a concerted action
                   1192:   from the European Union.
                   1193:   It is copyrighted identically to a GNU software product, ie programme and
                   1194:   software can be distributed freely for non commercial use. Latest version
                   1195:   can be accessed at http://euroreves.ined.fr/imach .
                   1196: 
                   1197:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1198:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1199:   
                   1200:   **********************************************************************/
                   1201: /*
                   1202:   main
                   1203:   read parameterfile
                   1204:   read datafile
                   1205:   concatwav
                   1206:   freqsummary
                   1207:   if (mle >= 1)
                   1208:     mlikeli
                   1209:   print results files
                   1210:   if mle==1 
                   1211:      computes hessian
                   1212:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1213:       begin-prev-date,...
                   1214:   open gnuplot file
                   1215:   open html file
1.145     brouard  1216:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1217:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1218:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1219:     freexexit2 possible for memory heap.
                   1220: 
                   1221:   h Pij x                         | pij_nom  ficrestpij
                   1222:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1223:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1224:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1225: 
                   1226:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1227:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1228:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1229:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1230:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1231: 
1.126     brouard  1232:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1233:   health expectancies
                   1234:   Variance-covariance of DFLE
                   1235:   prevalence()
                   1236:    movingaverage()
                   1237:   varevsij() 
                   1238:   if popbased==1 varevsij(,popbased)
                   1239:   total life expectancies
                   1240:   Variance of period (stable) prevalence
                   1241:  end
                   1242: */
                   1243: 
1.187     brouard  1244: /* #define DEBUG */
                   1245: /* #define DEBUGBRENT */
1.203     brouard  1246: /* #define DEBUGLINMIN */
                   1247: /* #define DEBUGHESS */
                   1248: #define DEBUGHESSIJ
1.224     brouard  1249: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1250: #define POWELL /* Instead of NLOPT */
1.224     brouard  1251: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1252: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1253: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1254: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1255: 
                   1256: #include <math.h>
                   1257: #include <stdio.h>
                   1258: #include <stdlib.h>
                   1259: #include <string.h>
1.226     brouard  1260: #include <ctype.h>
1.159     brouard  1261: 
                   1262: #ifdef _WIN32
                   1263: #include <io.h>
1.172     brouard  1264: #include <windows.h>
                   1265: #include <tchar.h>
1.159     brouard  1266: #else
1.126     brouard  1267: #include <unistd.h>
1.159     brouard  1268: #endif
1.126     brouard  1269: 
                   1270: #include <limits.h>
                   1271: #include <sys/types.h>
1.171     brouard  1272: 
                   1273: #if defined(__GNUC__)
                   1274: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1275: #endif
                   1276: 
1.126     brouard  1277: #include <sys/stat.h>
                   1278: #include <errno.h>
1.159     brouard  1279: /* extern int errno; */
1.126     brouard  1280: 
1.157     brouard  1281: /* #ifdef LINUX */
                   1282: /* #include <time.h> */
                   1283: /* #include "timeval.h" */
                   1284: /* #else */
                   1285: /* #include <sys/time.h> */
                   1286: /* #endif */
                   1287: 
1.126     brouard  1288: #include <time.h>
                   1289: 
1.136     brouard  1290: #ifdef GSL
                   1291: #include <gsl/gsl_errno.h>
                   1292: #include <gsl/gsl_multimin.h>
                   1293: #endif
                   1294: 
1.167     brouard  1295: 
1.162     brouard  1296: #ifdef NLOPT
                   1297: #include <nlopt.h>
                   1298: typedef struct {
                   1299:   double (* function)(double [] );
                   1300: } myfunc_data ;
                   1301: #endif
                   1302: 
1.126     brouard  1303: /* #include <libintl.h> */
                   1304: /* #define _(String) gettext (String) */
                   1305: 
1.251     brouard  1306: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1307: 
                   1308: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1309: #define GNUPLOTVERSION 5.1
                   1310: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1311: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1312: #define FILENAMELENGTH 256
1.126     brouard  1313: 
                   1314: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1315: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1316: 
1.144     brouard  1317: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1318: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1319: 
                   1320: #define NINTERVMAX 8
1.144     brouard  1321: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1322: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1323: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1324: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1325: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1326: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1327: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1328: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1329: /* #define AGESUP 130 */
1.288     brouard  1330: /* #define AGESUP 150 */
                   1331: #define AGESUP 200
1.268     brouard  1332: #define AGEINF 0
1.218     brouard  1333: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1334: #define AGEBASE 40
1.194     brouard  1335: #define AGEOVERFLOW 1.e20
1.164     brouard  1336: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1337: #ifdef _WIN32
                   1338: #define DIRSEPARATOR '\\'
                   1339: #define CHARSEPARATOR "\\"
                   1340: #define ODIRSEPARATOR '/'
                   1341: #else
1.126     brouard  1342: #define DIRSEPARATOR '/'
                   1343: #define CHARSEPARATOR "/"
                   1344: #define ODIRSEPARATOR '\\'
                   1345: #endif
                   1346: 
1.345   ! brouard  1347: /* $Id: imach.c,v 1.344 2022/09/14 19:33:30 brouard Exp $ */
1.126     brouard  1348: /* $State: Exp $ */
1.196     brouard  1349: #include "version.h"
                   1350: char version[]=__IMACH_VERSION__;
1.337     brouard  1351: char copyright[]="September 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.345   ! brouard  1352: char fullversion[]="$Revision: 1.344 $ $Date: 2022/09/14 19:33:30 $"; 
1.126     brouard  1353: char strstart[80];
                   1354: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1355: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1356: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1357: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1358: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1359: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1360: 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  1361: 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  1362: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1363: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1364: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1365: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1366: 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  1367: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1368: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1369: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1370: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1371: int nsd=0; /**< Total number of single dummy variables (output) */
                   1372: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1373: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1374: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1375: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1376: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1377: int cptcov=0; /* Working variable */
1.334     brouard  1378: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1379: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1380: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1381: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1382: int nlstate=2; /* Number of live states */
                   1383: int ndeath=1; /* Number of dead states */
1.130     brouard  1384: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1385: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1386: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1387: int popbased=0;
                   1388: 
                   1389: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1390: int maxwav=0; /* Maxim number of waves */
                   1391: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1392: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1393: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1394:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1395: int mle=1, weightopt=0;
1.126     brouard  1396: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1397: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1398: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1399:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1400: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1401: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1402: 
1.130     brouard  1403: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1404: double **matprod2(); /* test */
1.126     brouard  1405: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1406: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1407: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1408: 
1.136     brouard  1409: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1410: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1411: FILE *ficlog, *ficrespow;
1.130     brouard  1412: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1413: double fretone; /* Only one call to likelihood */
1.130     brouard  1414: long ipmx=0; /* Number of contributions */
1.126     brouard  1415: double sw; /* Sum of weights */
                   1416: char filerespow[FILENAMELENGTH];
                   1417: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1418: FILE *ficresilk;
                   1419: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1420: FILE *ficresprobmorprev;
                   1421: FILE *fichtm, *fichtmcov; /* Html File */
                   1422: FILE *ficreseij;
                   1423: char filerese[FILENAMELENGTH];
                   1424: FILE *ficresstdeij;
                   1425: char fileresstde[FILENAMELENGTH];
                   1426: FILE *ficrescveij;
                   1427: char filerescve[FILENAMELENGTH];
                   1428: FILE  *ficresvij;
                   1429: char fileresv[FILENAMELENGTH];
1.269     brouard  1430: 
1.126     brouard  1431: char title[MAXLINE];
1.234     brouard  1432: char model[MAXLINE]; /**< The model line */
1.217     brouard  1433: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1434: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1435: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1436: char command[FILENAMELENGTH];
                   1437: int  outcmd=0;
                   1438: 
1.217     brouard  1439: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1440: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1441: char filelog[FILENAMELENGTH]; /* Log file */
                   1442: char filerest[FILENAMELENGTH];
                   1443: char fileregp[FILENAMELENGTH];
                   1444: char popfile[FILENAMELENGTH];
                   1445: 
                   1446: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1447: 
1.157     brouard  1448: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1449: /* struct timezone tzp; */
                   1450: /* extern int gettimeofday(); */
                   1451: struct tm tml, *gmtime(), *localtime();
                   1452: 
                   1453: extern time_t time();
                   1454: 
                   1455: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1456: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1457: struct tm tm;
                   1458: 
1.126     brouard  1459: char strcurr[80], strfor[80];
                   1460: 
                   1461: char *endptr;
                   1462: long lval;
                   1463: double dval;
                   1464: 
                   1465: #define NR_END 1
                   1466: #define FREE_ARG char*
                   1467: #define FTOL 1.0e-10
                   1468: 
                   1469: #define NRANSI 
1.240     brouard  1470: #define ITMAX 200
                   1471: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1472: 
                   1473: #define TOL 2.0e-4 
                   1474: 
                   1475: #define CGOLD 0.3819660 
                   1476: #define ZEPS 1.0e-10 
                   1477: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1478: 
                   1479: #define GOLD 1.618034 
                   1480: #define GLIMIT 100.0 
                   1481: #define TINY 1.0e-20 
                   1482: 
                   1483: static double maxarg1,maxarg2;
                   1484: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1485: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1486:   
                   1487: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1488: #define rint(a) floor(a+0.5)
1.166     brouard  1489: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1490: #define mytinydouble 1.0e-16
1.166     brouard  1491: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1492: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1493: /* static double dsqrarg; */
                   1494: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1495: static double sqrarg;
                   1496: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1497: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1498: int agegomp= AGEGOMP;
                   1499: 
                   1500: int imx; 
                   1501: int stepm=1;
                   1502: /* Stepm, step in month: minimum step interpolation*/
                   1503: 
                   1504: int estepm;
                   1505: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1506: 
                   1507: int m,nb;
                   1508: long *num;
1.197     brouard  1509: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1510: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1511:                   covariate for which somebody answered excluding 
                   1512:                   undefined. Usually 2: 0 and 1. */
                   1513: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1514:                             covariate for which somebody answered including 
                   1515:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1516: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1517: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1518: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1519: 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  1520: double *ageexmed,*agecens;
                   1521: double dateintmean=0;
1.296     brouard  1522:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1523:   double anprojf, mprojf, jprojf;
1.126     brouard  1524: 
1.296     brouard  1525:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1526:   double anbackf, mbackf, jbackf;
                   1527:   double jintmean,mintmean,aintmean;  
1.126     brouard  1528: double *weight;
                   1529: int **s; /* Status */
1.141     brouard  1530: double *agedc;
1.145     brouard  1531: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1532:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1533:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1534: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1535: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1536: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1537: double  idx; 
                   1538: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1539: /* Some documentation */
                   1540:       /*   Design original data
                   1541:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1542:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1543:        *                                                             ntv=3     nqtv=1
1.330     brouard  1544:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1545:        * For time varying covariate, quanti or dummies
                   1546:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1547:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1548:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1549:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1550:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1551:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1552:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1553:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1554:        */
                   1555: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1556: /* 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
                   1557:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1558:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1559: */
1.343     brouard  1560: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1 */
                   1561: /*    kmodel  1  2   3   4     5    6    7     8    9 */
1.319     brouard  1562: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1563:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1564:                                                          /* product */
                   1565: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1566:                                                          /*(single or product without age), 2 dummy*/
                   1567:                                                          /* with age product, 3 quant with age product*/
                   1568: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1569: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1570: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1571: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1572: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1573: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1574: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1575: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1576: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1577: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1578: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1579: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1580: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1581: /* 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  1582: /* 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  1583: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1584: /* Type                    */
                   1585: /* V         1  2  3  4  5 */
                   1586: /*           F  F  V  V  V */
                   1587: /*           D  Q  D  D  Q */
                   1588: /*                         */
                   1589: int *TvarsD;
1.330     brouard  1590: int *TnsdVar;
1.234     brouard  1591: int *TvarsDind;
                   1592: int *TvarsQ;
                   1593: int *TvarsQind;
                   1594: 
1.318     brouard  1595: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1596: int nresult=0;
1.258     brouard  1597: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1598: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1599: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1600: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1601: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1602: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1603: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1604: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1605: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1606: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1607: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1608: 
                   1609: /* 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
                   1610:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1611:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1612: */
1.234     brouard  1613: /* 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  1614: 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 */
                   1615: 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 */
                   1616: 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 */
                   1617: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1618: 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 */
                   1619: 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  1620: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1621: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1622: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1623: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1624: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1625: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1626: 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 */
                   1627: 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  1628: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1629: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1630:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1631:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1632:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1633:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1634:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1635: int *Tvarsel; /**< Selected covariates for output */
                   1636: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1637: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1638: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1639: 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  1640: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1641: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1642: int *Tage;
1.227     brouard  1643: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1644: 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  1645: 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*/ 
                   1646: 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  1647: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1648: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1649: int **Tvard;
1.330     brouard  1650: int **Tvardk;
1.227     brouard  1651: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1652: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1653: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1654:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1655:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1656: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1657: double *lsurv, *lpop, *tpop;
                   1658: 
1.231     brouard  1659: #define FD 1; /* Fixed dummy covariate */
                   1660: #define FQ 2; /* Fixed quantitative covariate */
                   1661: #define FP 3; /* Fixed product covariate */
                   1662: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1663: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1664: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1665: #define VD 10; /* Varying dummy covariate */
                   1666: #define VQ 11; /* Varying quantitative covariate */
                   1667: #define VP 12; /* Varying product covariate */
                   1668: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1669: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1670: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1671: #define APFD 16; /* Age product * fixed dummy covariate */
                   1672: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1673: #define APVD 18; /* Age product * varying dummy covariate */
                   1674: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1675: 
                   1676: #define FTYPE 1; /* Fixed covariate */
                   1677: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1678: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1679: 
                   1680: struct kmodel{
                   1681:        int maintype; /* main type */
                   1682:        int subtype; /* subtype */
                   1683: };
                   1684: struct kmodel modell[NCOVMAX];
                   1685: 
1.143     brouard  1686: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1687: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1688: 
                   1689: /**************** split *************************/
                   1690: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1691: {
                   1692:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1693:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1694:   */ 
                   1695:   char *ss;                            /* pointer */
1.186     brouard  1696:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1697: 
                   1698:   l1 = strlen(path );                  /* length of path */
                   1699:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1700:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1701:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1702:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1703:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1704:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1705:     /* get current working directory */
                   1706:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1707: #ifdef WIN32
                   1708:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1709: #else
                   1710:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1711: #endif
1.126     brouard  1712:       return( GLOCK_ERROR_GETCWD );
                   1713:     }
                   1714:     /* got dirc from getcwd*/
                   1715:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1716:   } else {                             /* strip directory from path */
1.126     brouard  1717:     ss++;                              /* after this, the filename */
                   1718:     l2 = strlen( ss );                 /* length of filename */
                   1719:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1720:     strcpy( name, ss );                /* save file name */
                   1721:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1722:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1723:     printf(" DIRC2 = %s \n",dirc);
                   1724:   }
                   1725:   /* We add a separator at the end of dirc if not exists */
                   1726:   l1 = strlen( dirc );                 /* length of directory */
                   1727:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1728:     dirc[l1] =  DIRSEPARATOR;
                   1729:     dirc[l1+1] = 0; 
                   1730:     printf(" DIRC3 = %s \n",dirc);
                   1731:   }
                   1732:   ss = strrchr( name, '.' );           /* find last / */
                   1733:   if (ss >0){
                   1734:     ss++;
                   1735:     strcpy(ext,ss);                    /* save extension */
                   1736:     l1= strlen( name);
                   1737:     l2= strlen(ss)+1;
                   1738:     strncpy( finame, name, l1-l2);
                   1739:     finame[l1-l2]= 0;
                   1740:   }
                   1741: 
                   1742:   return( 0 );                         /* we're done */
                   1743: }
                   1744: 
                   1745: 
                   1746: /******************************************/
                   1747: 
                   1748: void replace_back_to_slash(char *s, char*t)
                   1749: {
                   1750:   int i;
                   1751:   int lg=0;
                   1752:   i=0;
                   1753:   lg=strlen(t);
                   1754:   for(i=0; i<= lg; i++) {
                   1755:     (s[i] = t[i]);
                   1756:     if (t[i]== '\\') s[i]='/';
                   1757:   }
                   1758: }
                   1759: 
1.132     brouard  1760: char *trimbb(char *out, char *in)
1.137     brouard  1761: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1762:   char *s;
                   1763:   s=out;
                   1764:   while (*in != '\0'){
1.137     brouard  1765:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1766:       in++;
                   1767:     }
                   1768:     *out++ = *in++;
                   1769:   }
                   1770:   *out='\0';
                   1771:   return s;
                   1772: }
                   1773: 
1.187     brouard  1774: /* char *substrchaine(char *out, char *in, char *chain) */
                   1775: /* { */
                   1776: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1777: /*   char *s, *t; */
                   1778: /*   t=in;s=out; */
                   1779: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1780: /*     *out++ = *in++; */
                   1781: /*   } */
                   1782: 
                   1783: /*   /\* *in matches *chain *\/ */
                   1784: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1785: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1786: /*   } */
                   1787: /*   in--; chain--; */
                   1788: /*   while ( (*in != '\0')){ */
                   1789: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1790: /*     *out++ = *in++; */
                   1791: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1792: /*   } */
                   1793: /*   *out='\0'; */
                   1794: /*   out=s; */
                   1795: /*   return out; */
                   1796: /* } */
                   1797: char *substrchaine(char *out, char *in, char *chain)
                   1798: {
                   1799:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1800:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1801: 
                   1802:   char *strloc;
                   1803: 
                   1804:   strcpy (out, in); 
                   1805:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1806:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1807:   if(strloc != NULL){ 
                   1808:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1809:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1810:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1811:   }
                   1812:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1813:   return out;
                   1814: }
                   1815: 
                   1816: 
1.145     brouard  1817: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1818: {
1.187     brouard  1819:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1820:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1821:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1822:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1823:   */
1.160     brouard  1824:   char *s, *t;
1.145     brouard  1825:   t=in;s=in;
                   1826:   while ((*in != occ) && (*in != '\0')){
                   1827:     *alocc++ = *in++;
                   1828:   }
                   1829:   if( *in == occ){
                   1830:     *(alocc)='\0';
                   1831:     s=++in;
                   1832:   }
                   1833:  
                   1834:   if (s == t) {/* occ not found */
                   1835:     *(alocc-(in-s))='\0';
                   1836:     in=s;
                   1837:   }
                   1838:   while ( *in != '\0'){
                   1839:     *blocc++ = *in++;
                   1840:   }
                   1841: 
                   1842:   *blocc='\0';
                   1843:   return t;
                   1844: }
1.137     brouard  1845: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1846: {
1.187     brouard  1847:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1848:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1849:      gives blocc="abcdef2ghi" and alocc="j".
                   1850:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1851:   */
                   1852:   char *s, *t;
                   1853:   t=in;s=in;
                   1854:   while (*in != '\0'){
                   1855:     while( *in == occ){
                   1856:       *blocc++ = *in++;
                   1857:       s=in;
                   1858:     }
                   1859:     *blocc++ = *in++;
                   1860:   }
                   1861:   if (s == t) /* occ not found */
                   1862:     *(blocc-(in-s))='\0';
                   1863:   else
                   1864:     *(blocc-(in-s)-1)='\0';
                   1865:   in=s;
                   1866:   while ( *in != '\0'){
                   1867:     *alocc++ = *in++;
                   1868:   }
                   1869: 
                   1870:   *alocc='\0';
                   1871:   return s;
                   1872: }
                   1873: 
1.126     brouard  1874: int nbocc(char *s, char occ)
                   1875: {
                   1876:   int i,j=0;
                   1877:   int lg=20;
                   1878:   i=0;
                   1879:   lg=strlen(s);
                   1880:   for(i=0; i<= lg; i++) {
1.234     brouard  1881:     if  (s[i] == occ ) j++;
1.126     brouard  1882:   }
                   1883:   return j;
                   1884: }
                   1885: 
1.137     brouard  1886: /* void cutv(char *u,char *v, char*t, char occ) */
                   1887: /* { */
                   1888: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1889: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1890: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1891: /*   int i,lg,j,p=0; */
                   1892: /*   i=0; */
                   1893: /*   lg=strlen(t); */
                   1894: /*   for(j=0; j<=lg-1; j++) { */
                   1895: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1896: /*   } */
1.126     brouard  1897: 
1.137     brouard  1898: /*   for(j=0; j<p; j++) { */
                   1899: /*     (u[j] = t[j]); */
                   1900: /*   } */
                   1901: /*      u[p]='\0'; */
1.126     brouard  1902: 
1.137     brouard  1903: /*    for(j=0; j<= lg; j++) { */
                   1904: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1905: /*   } */
                   1906: /* } */
1.126     brouard  1907: 
1.160     brouard  1908: #ifdef _WIN32
                   1909: char * strsep(char **pp, const char *delim)
                   1910: {
                   1911:   char *p, *q;
                   1912:          
                   1913:   if ((p = *pp) == NULL)
                   1914:     return 0;
                   1915:   if ((q = strpbrk (p, delim)) != NULL)
                   1916:   {
                   1917:     *pp = q + 1;
                   1918:     *q = '\0';
                   1919:   }
                   1920:   else
                   1921:     *pp = 0;
                   1922:   return p;
                   1923: }
                   1924: #endif
                   1925: 
1.126     brouard  1926: /********************** nrerror ********************/
                   1927: 
                   1928: void nrerror(char error_text[])
                   1929: {
                   1930:   fprintf(stderr,"ERREUR ...\n");
                   1931:   fprintf(stderr,"%s\n",error_text);
                   1932:   exit(EXIT_FAILURE);
                   1933: }
                   1934: /*********************** vector *******************/
                   1935: double *vector(int nl, int nh)
                   1936: {
                   1937:   double *v;
                   1938:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1939:   if (!v) nrerror("allocation failure in vector");
                   1940:   return v-nl+NR_END;
                   1941: }
                   1942: 
                   1943: /************************ free vector ******************/
                   1944: void free_vector(double*v, int nl, int nh)
                   1945: {
                   1946:   free((FREE_ARG)(v+nl-NR_END));
                   1947: }
                   1948: 
                   1949: /************************ivector *******************************/
                   1950: int *ivector(long nl,long nh)
                   1951: {
                   1952:   int *v;
                   1953:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1954:   if (!v) nrerror("allocation failure in ivector");
                   1955:   return v-nl+NR_END;
                   1956: }
                   1957: 
                   1958: /******************free ivector **************************/
                   1959: void free_ivector(int *v, long nl, long nh)
                   1960: {
                   1961:   free((FREE_ARG)(v+nl-NR_END));
                   1962: }
                   1963: 
                   1964: /************************lvector *******************************/
                   1965: long *lvector(long nl,long nh)
                   1966: {
                   1967:   long *v;
                   1968:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1969:   if (!v) nrerror("allocation failure in ivector");
                   1970:   return v-nl+NR_END;
                   1971: }
                   1972: 
                   1973: /******************free lvector **************************/
                   1974: void free_lvector(long *v, long nl, long nh)
                   1975: {
                   1976:   free((FREE_ARG)(v+nl-NR_END));
                   1977: }
                   1978: 
                   1979: /******************* imatrix *******************************/
                   1980: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1981:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1982: { 
                   1983:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1984:   int **m; 
                   1985:   
                   1986:   /* allocate pointers to rows */ 
                   1987:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1988:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1989:   m += NR_END; 
                   1990:   m -= nrl; 
                   1991:   
                   1992:   
                   1993:   /* allocate rows and set pointers to them */ 
                   1994:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1995:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1996:   m[nrl] += NR_END; 
                   1997:   m[nrl] -= ncl; 
                   1998:   
                   1999:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2000:   
                   2001:   /* return pointer to array of pointers to rows */ 
                   2002:   return m; 
                   2003: } 
                   2004: 
                   2005: /****************** free_imatrix *************************/
                   2006: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2007:       int **m;
                   2008:       long nch,ncl,nrh,nrl; 
                   2009:      /* free an int matrix allocated by imatrix() */ 
                   2010: { 
                   2011:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2012:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2013: } 
                   2014: 
                   2015: /******************* matrix *******************************/
                   2016: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2017: {
                   2018:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2019:   double **m;
                   2020: 
                   2021:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2022:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2023:   m += NR_END;
                   2024:   m -= nrl;
                   2025: 
                   2026:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2027:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2028:   m[nrl] += NR_END;
                   2029:   m[nrl] -= ncl;
                   2030: 
                   2031:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2032:   return m;
1.145     brouard  2033:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2034: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2035: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2036:    */
                   2037: }
                   2038: 
                   2039: /*************************free matrix ************************/
                   2040: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2041: {
                   2042:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2043:   free((FREE_ARG)(m+nrl-NR_END));
                   2044: }
                   2045: 
                   2046: /******************* ma3x *******************************/
                   2047: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2048: {
                   2049:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2050:   double ***m;
                   2051: 
                   2052:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2053:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2054:   m += NR_END;
                   2055:   m -= nrl;
                   2056: 
                   2057:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2058:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2059:   m[nrl] += NR_END;
                   2060:   m[nrl] -= ncl;
                   2061: 
                   2062:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2063: 
                   2064:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2065:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2066:   m[nrl][ncl] += NR_END;
                   2067:   m[nrl][ncl] -= nll;
                   2068:   for (j=ncl+1; j<=nch; j++) 
                   2069:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2070:   
                   2071:   for (i=nrl+1; i<=nrh; i++) {
                   2072:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2073:     for (j=ncl+1; j<=nch; j++) 
                   2074:       m[i][j]=m[i][j-1]+nlay;
                   2075:   }
                   2076:   return m; 
                   2077:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2078:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2079:   */
                   2080: }
                   2081: 
                   2082: /*************************free ma3x ************************/
                   2083: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2084: {
                   2085:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2086:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2087:   free((FREE_ARG)(m+nrl-NR_END));
                   2088: }
                   2089: 
                   2090: /*************** function subdirf ***********/
                   2091: char *subdirf(char fileres[])
                   2092: {
                   2093:   /* Caution optionfilefiname is hidden */
                   2094:   strcpy(tmpout,optionfilefiname);
                   2095:   strcat(tmpout,"/"); /* Add to the right */
                   2096:   strcat(tmpout,fileres);
                   2097:   return tmpout;
                   2098: }
                   2099: 
                   2100: /*************** function subdirf2 ***********/
                   2101: char *subdirf2(char fileres[], char *preop)
                   2102: {
1.314     brouard  2103:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2104:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2105:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2106:   /* Caution optionfilefiname is hidden */
                   2107:   strcpy(tmpout,optionfilefiname);
                   2108:   strcat(tmpout,"/");
                   2109:   strcat(tmpout,preop);
                   2110:   strcat(tmpout,fileres);
                   2111:   return tmpout;
                   2112: }
                   2113: 
                   2114: /*************** function subdirf3 ***********/
                   2115: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2116: {
                   2117:   
                   2118:   /* Caution optionfilefiname is hidden */
                   2119:   strcpy(tmpout,optionfilefiname);
                   2120:   strcat(tmpout,"/");
                   2121:   strcat(tmpout,preop);
                   2122:   strcat(tmpout,preop2);
                   2123:   strcat(tmpout,fileres);
                   2124:   return tmpout;
                   2125: }
1.213     brouard  2126:  
                   2127: /*************** function subdirfext ***********/
                   2128: char *subdirfext(char fileres[], char *preop, char *postop)
                   2129: {
                   2130:   
                   2131:   strcpy(tmpout,preop);
                   2132:   strcat(tmpout,fileres);
                   2133:   strcat(tmpout,postop);
                   2134:   return tmpout;
                   2135: }
1.126     brouard  2136: 
1.213     brouard  2137: /*************** function subdirfext3 ***********/
                   2138: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2139: {
                   2140:   
                   2141:   /* Caution optionfilefiname is hidden */
                   2142:   strcpy(tmpout,optionfilefiname);
                   2143:   strcat(tmpout,"/");
                   2144:   strcat(tmpout,preop);
                   2145:   strcat(tmpout,fileres);
                   2146:   strcat(tmpout,postop);
                   2147:   return tmpout;
                   2148: }
                   2149:  
1.162     brouard  2150: char *asc_diff_time(long time_sec, char ascdiff[])
                   2151: {
                   2152:   long sec_left, days, hours, minutes;
                   2153:   days = (time_sec) / (60*60*24);
                   2154:   sec_left = (time_sec) % (60*60*24);
                   2155:   hours = (sec_left) / (60*60) ;
                   2156:   sec_left = (sec_left) %(60*60);
                   2157:   minutes = (sec_left) /60;
                   2158:   sec_left = (sec_left) % (60);
                   2159:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2160:   return ascdiff;
                   2161: }
                   2162: 
1.126     brouard  2163: /***************** f1dim *************************/
                   2164: extern int ncom; 
                   2165: extern double *pcom,*xicom;
                   2166: extern double (*nrfunc)(double []); 
                   2167:  
                   2168: double f1dim(double x) 
                   2169: { 
                   2170:   int j; 
                   2171:   double f;
                   2172:   double *xt; 
                   2173:  
                   2174:   xt=vector(1,ncom); 
                   2175:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2176:   f=(*nrfunc)(xt); 
                   2177:   free_vector(xt,1,ncom); 
                   2178:   return f; 
                   2179: } 
                   2180: 
                   2181: /*****************brent *************************/
                   2182: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2183: {
                   2184:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2185:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2186:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2187:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2188:    * returned function value. 
                   2189:   */
1.126     brouard  2190:   int iter; 
                   2191:   double a,b,d,etemp;
1.159     brouard  2192:   double fu=0,fv,fw,fx;
1.164     brouard  2193:   double ftemp=0.;
1.126     brouard  2194:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2195:   double e=0.0; 
                   2196:  
                   2197:   a=(ax < cx ? ax : cx); 
                   2198:   b=(ax > cx ? ax : cx); 
                   2199:   x=w=v=bx; 
                   2200:   fw=fv=fx=(*f)(x); 
                   2201:   for (iter=1;iter<=ITMAX;iter++) { 
                   2202:     xm=0.5*(a+b); 
                   2203:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2204:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2205:     printf(".");fflush(stdout);
                   2206:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2207: #ifdef DEBUGBRENT
1.126     brouard  2208:     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);
                   2209:     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);
                   2210:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2211: #endif
                   2212:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2213:       *xmin=x; 
                   2214:       return fx; 
                   2215:     } 
                   2216:     ftemp=fu;
                   2217:     if (fabs(e) > tol1) { 
                   2218:       r=(x-w)*(fx-fv); 
                   2219:       q=(x-v)*(fx-fw); 
                   2220:       p=(x-v)*q-(x-w)*r; 
                   2221:       q=2.0*(q-r); 
                   2222:       if (q > 0.0) p = -p; 
                   2223:       q=fabs(q); 
                   2224:       etemp=e; 
                   2225:       e=d; 
                   2226:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2227:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2228:       else { 
1.224     brouard  2229:                                d=p/q; 
                   2230:                                u=x+d; 
                   2231:                                if (u-a < tol2 || b-u < tol2) 
                   2232:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2233:       } 
                   2234:     } else { 
                   2235:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2236:     } 
                   2237:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2238:     fu=(*f)(u); 
                   2239:     if (fu <= fx) { 
                   2240:       if (u >= x) a=x; else b=x; 
                   2241:       SHFT(v,w,x,u) 
1.183     brouard  2242:       SHFT(fv,fw,fx,fu) 
                   2243:     } else { 
                   2244:       if (u < x) a=u; else b=u; 
                   2245:       if (fu <= fw || w == x) { 
1.224     brouard  2246:                                v=w; 
                   2247:                                w=u; 
                   2248:                                fv=fw; 
                   2249:                                fw=fu; 
1.183     brouard  2250:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2251:                                v=u; 
                   2252:                                fv=fu; 
1.183     brouard  2253:       } 
                   2254:     } 
1.126     brouard  2255:   } 
                   2256:   nrerror("Too many iterations in brent"); 
                   2257:   *xmin=x; 
                   2258:   return fx; 
                   2259: } 
                   2260: 
                   2261: /****************** mnbrak ***********************/
                   2262: 
                   2263: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2264:            double (*func)(double)) 
1.183     brouard  2265: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2266: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2267: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2268: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2269:    */
1.126     brouard  2270:   double ulim,u,r,q, dum;
                   2271:   double fu; 
1.187     brouard  2272: 
                   2273:   double scale=10.;
                   2274:   int iterscale=0;
                   2275: 
                   2276:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2277:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2278: 
                   2279: 
                   2280:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2281:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2282:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2283:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2284:   /* } */
                   2285: 
1.126     brouard  2286:   if (*fb > *fa) { 
                   2287:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2288:     SHFT(dum,*fb,*fa,dum) 
                   2289:   } 
1.126     brouard  2290:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2291:   *fc=(*func)(*cx); 
1.183     brouard  2292: #ifdef DEBUG
1.224     brouard  2293:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2294:   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  2295: #endif
1.224     brouard  2296:   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  2297:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2298:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2299:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2300:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2301:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2302:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2303:       fu=(*func)(u); 
1.163     brouard  2304: #ifdef DEBUG
                   2305:       /* f(x)=A(x-u)**2+f(u) */
                   2306:       double A, fparabu; 
                   2307:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2308:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2309:       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);
                   2310:       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  2311:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2312:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2313:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2314:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2315: #endif 
1.184     brouard  2316: #ifdef MNBRAKORIGINAL
1.183     brouard  2317: #else
1.191     brouard  2318: /*       if (fu > *fc) { */
                   2319: /* #ifdef DEBUG */
                   2320: /*       printf("mnbrak4  fu > fc \n"); */
                   2321: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2322: /* #endif */
                   2323: /*     /\* 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 *\\/  *\/ */
                   2324: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2325: /*     dum=u; /\* Shifting c and u *\/ */
                   2326: /*     u = *cx; */
                   2327: /*     *cx = dum; */
                   2328: /*     dum = fu; */
                   2329: /*     fu = *fc; */
                   2330: /*     *fc =dum; */
                   2331: /*       } else { /\* end *\/ */
                   2332: /* #ifdef DEBUG */
                   2333: /*       printf("mnbrak3  fu < fc \n"); */
                   2334: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2335: /* #endif */
                   2336: /*     dum=u; /\* Shifting c and u *\/ */
                   2337: /*     u = *cx; */
                   2338: /*     *cx = dum; */
                   2339: /*     dum = fu; */
                   2340: /*     fu = *fc; */
                   2341: /*     *fc =dum; */
                   2342: /*       } */
1.224     brouard  2343: #ifdef DEBUGMNBRAK
                   2344:                 double A, fparabu; 
                   2345:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2346:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2347:      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);
                   2348:      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  2349: #endif
1.191     brouard  2350:       dum=u; /* Shifting c and u */
                   2351:       u = *cx;
                   2352:       *cx = dum;
                   2353:       dum = fu;
                   2354:       fu = *fc;
                   2355:       *fc =dum;
1.183     brouard  2356: #endif
1.162     brouard  2357:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2358: #ifdef DEBUG
1.224     brouard  2359:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2360:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2361: #endif
1.126     brouard  2362:       fu=(*func)(u); 
                   2363:       if (fu < *fc) { 
1.183     brouard  2364: #ifdef DEBUG
1.224     brouard  2365:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2366:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2367: #endif
                   2368:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2369:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2370: #ifdef DEBUG
                   2371:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2372: #endif
                   2373:       } 
1.162     brouard  2374:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2375: #ifdef DEBUG
1.224     brouard  2376:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2377:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2378: #endif
1.126     brouard  2379:       u=ulim; 
                   2380:       fu=(*func)(u); 
1.183     brouard  2381:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2382: #ifdef DEBUG
1.224     brouard  2383:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2384:       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  2385: #endif
1.126     brouard  2386:       u=(*cx)+GOLD*(*cx-*bx); 
                   2387:       fu=(*func)(u); 
1.224     brouard  2388: #ifdef DEBUG
                   2389:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2390:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2391: #endif
1.183     brouard  2392:     } /* end tests */
1.126     brouard  2393:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2394:     SHFT(*fa,*fb,*fc,fu) 
                   2395: #ifdef DEBUG
1.224     brouard  2396:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2397:       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  2398: #endif
                   2399:   } /* 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  2400: } 
                   2401: 
                   2402: /*************** linmin ************************/
1.162     brouard  2403: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2404: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2405: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2406: the value of func at the returned location p . This is actually all accomplished by calling the
                   2407: routines mnbrak and brent .*/
1.126     brouard  2408: int ncom; 
                   2409: double *pcom,*xicom;
                   2410: double (*nrfunc)(double []); 
                   2411:  
1.224     brouard  2412: #ifdef LINMINORIGINAL
1.126     brouard  2413: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2414: #else
                   2415: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2416: #endif
1.126     brouard  2417: { 
                   2418:   double brent(double ax, double bx, double cx, 
                   2419:               double (*f)(double), double tol, double *xmin); 
                   2420:   double f1dim(double x); 
                   2421:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2422:              double *fc, double (*func)(double)); 
                   2423:   int j; 
                   2424:   double xx,xmin,bx,ax; 
                   2425:   double fx,fb,fa;
1.187     brouard  2426: 
1.203     brouard  2427: #ifdef LINMINORIGINAL
                   2428: #else
                   2429:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2430: #endif
                   2431:   
1.126     brouard  2432:   ncom=n; 
                   2433:   pcom=vector(1,n); 
                   2434:   xicom=vector(1,n); 
                   2435:   nrfunc=func; 
                   2436:   for (j=1;j<=n;j++) { 
                   2437:     pcom[j]=p[j]; 
1.202     brouard  2438:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2439:   } 
1.187     brouard  2440: 
1.203     brouard  2441: #ifdef LINMINORIGINAL
                   2442:   xx=1.;
                   2443: #else
                   2444:   axs=0.0;
                   2445:   xxs=1.;
                   2446:   do{
                   2447:     xx= xxs;
                   2448: #endif
1.187     brouard  2449:     ax=0.;
                   2450:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2451:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2452:     /* 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))   */
                   2453:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2454:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2455:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2456:     /* 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  2457: #ifdef LINMINORIGINAL
                   2458: #else
                   2459:     if (fx != fx){
1.224     brouard  2460:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2461:                        printf("|");
                   2462:                        fprintf(ficlog,"|");
1.203     brouard  2463: #ifdef DEBUGLINMIN
1.224     brouard  2464:                        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  2465: #endif
                   2466:     }
1.224     brouard  2467:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2468: #endif
                   2469:   
1.191     brouard  2470: #ifdef DEBUGLINMIN
                   2471:   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  2472:   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  2473: #endif
1.224     brouard  2474: #ifdef LINMINORIGINAL
                   2475: #else
1.317     brouard  2476:   if(fb == fx){ /* Flat function in the direction */
                   2477:     xmin=xx;
1.224     brouard  2478:     *flat=1;
1.317     brouard  2479:   }else{
1.224     brouard  2480:     *flat=0;
                   2481: #endif
                   2482:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2483:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2484:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2485:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2486:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2487:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2488: #ifdef DEBUG
1.224     brouard  2489:   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);
                   2490:   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);
                   2491: #endif
                   2492: #ifdef LINMINORIGINAL
                   2493: #else
                   2494:                        }
1.126     brouard  2495: #endif
1.191     brouard  2496: #ifdef DEBUGLINMIN
                   2497:   printf("linmin end ");
1.202     brouard  2498:   fprintf(ficlog,"linmin end ");
1.191     brouard  2499: #endif
1.126     brouard  2500:   for (j=1;j<=n;j++) { 
1.203     brouard  2501: #ifdef LINMINORIGINAL
                   2502:     xi[j] *= xmin; 
                   2503: #else
                   2504: #ifdef DEBUGLINMIN
                   2505:     if(xxs <1.0)
                   2506:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2507: #endif
                   2508:     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) */
                   2509: #ifdef DEBUGLINMIN
                   2510:     if(xxs <1.0)
                   2511:       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 );
                   2512: #endif
                   2513: #endif
1.187     brouard  2514:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2515:   } 
1.191     brouard  2516: #ifdef DEBUGLINMIN
1.203     brouard  2517:   printf("\n");
1.191     brouard  2518:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2519:   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  2520:   for (j=1;j<=n;j++) { 
1.202     brouard  2521:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2522:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2523:     if(j % ncovmodel == 0){
1.191     brouard  2524:       printf("\n");
1.202     brouard  2525:       fprintf(ficlog,"\n");
                   2526:     }
1.191     brouard  2527:   }
1.203     brouard  2528: #else
1.191     brouard  2529: #endif
1.126     brouard  2530:   free_vector(xicom,1,n); 
                   2531:   free_vector(pcom,1,n); 
                   2532: } 
                   2533: 
                   2534: 
                   2535: /*************** powell ************************/
1.162     brouard  2536: /*
1.317     brouard  2537: Minimization of a function func of n variables. Input consists in an initial starting point
                   2538: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2539: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2540: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2541: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2542: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2543:  */
1.224     brouard  2544: #ifdef LINMINORIGINAL
                   2545: #else
                   2546:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2547:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2548: #endif
1.126     brouard  2549: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2550:            double (*func)(double [])) 
                   2551: { 
1.224     brouard  2552: #ifdef LINMINORIGINAL
                   2553:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2554:              double (*func)(double [])); 
1.224     brouard  2555: #else 
1.241     brouard  2556:  void linmin(double p[], double xi[], int n, double *fret,
                   2557:             double (*func)(double []),int *flat); 
1.224     brouard  2558: #endif
1.239     brouard  2559:  int i,ibig,j,jk,k; 
1.126     brouard  2560:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2561:   double directest;
1.126     brouard  2562:   double fp,fptt;
                   2563:   double *xits;
                   2564:   int niterf, itmp;
                   2565: 
                   2566:   pt=vector(1,n); 
                   2567:   ptt=vector(1,n); 
                   2568:   xit=vector(1,n); 
                   2569:   xits=vector(1,n); 
                   2570:   *fret=(*func)(p); 
                   2571:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2572:   rcurr_time = time(NULL);
                   2573:   fp=(*fret); /* Initialisation */
1.126     brouard  2574:   for (*iter=1;;++(*iter)) { 
                   2575:     ibig=0; 
                   2576:     del=0.0; 
1.157     brouard  2577:     rlast_time=rcurr_time;
                   2578:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2579:     rcurr_time = time(NULL);  
                   2580:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2581:     /* 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); */
                   2582:     /* 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); */
                   2583:     printf("\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2584:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2585: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2586:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2587:     for (i=1;i<=n;i++) {
1.126     brouard  2588:       fprintf(ficrespow," %.12lf", p[i]);
                   2589:     }
1.239     brouard  2590:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2591:     printf("\n#model=  1      +     age ");
                   2592:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2593:     if(nagesqr==1){
1.241     brouard  2594:        printf("  + age*age  ");
                   2595:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2596:     }
                   2597:     for(j=1;j <=ncovmodel-2;j++){
                   2598:       if(Typevar[j]==0) {
                   2599:        printf("  +      V%d  ",Tvar[j]);
                   2600:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2601:       }else if(Typevar[j]==1) {
                   2602:        printf("  +    V%d*age ",Tvar[j]);
                   2603:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2604:       }else if(Typevar[j]==2) {
                   2605:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2606:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2607:       }
                   2608:     }
1.126     brouard  2609:     printf("\n");
1.239     brouard  2610: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2611: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2612:     fprintf(ficlog,"\n");
1.239     brouard  2613:     for(i=1,jk=1; i <=nlstate; i++){
                   2614:       for(k=1; k <=(nlstate+ndeath); k++){
                   2615:        if (k != i) {
                   2616:          printf("%d%d ",i,k);
                   2617:          fprintf(ficlog,"%d%d ",i,k);
                   2618:          for(j=1; j <=ncovmodel; j++){
                   2619:            printf("%12.7f ",p[jk]);
                   2620:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2621:            jk++; 
                   2622:          }
                   2623:          printf("\n");
                   2624:          fprintf(ficlog,"\n");
                   2625:        }
                   2626:       }
                   2627:     }
1.241     brouard  2628:     if(*iter <=3 && *iter >1){
1.157     brouard  2629:       tml = *localtime(&rcurr_time);
                   2630:       strcpy(strcurr,asctime(&tml));
                   2631:       rforecast_time=rcurr_time; 
1.126     brouard  2632:       itmp = strlen(strcurr);
                   2633:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2634:        strcurr[itmp-1]='\0';
1.162     brouard  2635:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2636:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2637:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2638:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2639:        forecast_time = *localtime(&rforecast_time);
                   2640:        strcpy(strfor,asctime(&forecast_time));
                   2641:        itmp = strlen(strfor);
                   2642:        if(strfor[itmp-1]=='\n')
                   2643:          strfor[itmp-1]='\0';
                   2644:        printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   2645:        fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  2646:       }
                   2647:     }
1.187     brouard  2648:     for (i=1;i<=n;i++) { /* For each direction i */
                   2649:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2650:       fptt=(*fret); 
                   2651: #ifdef DEBUG
1.203     brouard  2652:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2653:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2654: #endif
1.203     brouard  2655:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2656:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2657: #ifdef LINMINORIGINAL
1.188     brouard  2658:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2659: #else
                   2660:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2661:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2662: #endif
                   2663:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2664:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2665:                                /* because that direction will be replaced unless the gain del is small */
                   2666:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2667:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2668:                                /* with the new direction. */
                   2669:                                del=fabs(fptt-(*fret)); 
                   2670:                                ibig=i; 
1.126     brouard  2671:       } 
                   2672: #ifdef DEBUG
                   2673:       printf("%d %.12e",i,(*fret));
                   2674:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2675:       for (j=1;j<=n;j++) {
1.224     brouard  2676:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2677:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2678:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2679:       }
                   2680:       for(j=1;j<=n;j++) {
1.225     brouard  2681:                                printf(" p(%d)=%.12e",j,p[j]);
                   2682:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2683:       }
                   2684:       printf("\n");
                   2685:       fprintf(ficlog,"\n");
                   2686: #endif
1.187     brouard  2687:     } /* end loop on each direction i */
                   2688:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2689:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2690:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2691:     for(j=1;j<=n;j++) {
                   2692:       if(flatdir[j] >0){
                   2693:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2694:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2695:       }
1.319     brouard  2696:       /* printf("\n"); */
                   2697:       /* fprintf(ficlog,"\n"); */
                   2698:     }
1.243     brouard  2699:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2700:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2701:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2702:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2703:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2704:       /* decreased of more than 3.84  */
                   2705:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2706:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2707:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2708:                        
1.188     brouard  2709:       /* Starting the program with initial values given by a former maximization will simply change */
                   2710:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2711:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2712:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2713: #ifdef DEBUG
                   2714:       int k[2],l;
                   2715:       k[0]=1;
                   2716:       k[1]=-1;
                   2717:       printf("Max: %.12e",(*func)(p));
                   2718:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2719:       for (j=1;j<=n;j++) {
                   2720:        printf(" %.12e",p[j]);
                   2721:        fprintf(ficlog," %.12e",p[j]);
                   2722:       }
                   2723:       printf("\n");
                   2724:       fprintf(ficlog,"\n");
                   2725:       for(l=0;l<=1;l++) {
                   2726:        for (j=1;j<=n;j++) {
                   2727:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2728:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2729:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2730:        }
                   2731:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2732:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2733:       }
                   2734: #endif
                   2735: 
                   2736:       free_vector(xit,1,n); 
                   2737:       free_vector(xits,1,n); 
                   2738:       free_vector(ptt,1,n); 
                   2739:       free_vector(pt,1,n); 
                   2740:       return; 
1.192     brouard  2741:     } /* enough precision */ 
1.240     brouard  2742:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2743:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2744:       ptt[j]=2.0*p[j]-pt[j]; 
                   2745:       xit[j]=p[j]-pt[j]; 
                   2746:       pt[j]=p[j]; 
                   2747:     } 
1.181     brouard  2748:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2749: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2750:                if (*iter <=4) {
1.225     brouard  2751: #else
                   2752: #endif
1.224     brouard  2753: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2754: #else
1.161     brouard  2755:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2756: #endif
1.162     brouard  2757:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2758:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2759:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2760:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2761:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2762:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2763:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2764:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2765:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2766:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2767:       /* mu² and del² are equal when f3=f1 */
                   2768:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2769:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2770:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2771:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2772: #ifdef NRCORIGINAL
                   2773:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2774: #else
                   2775:       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  2776:       t= t- del*SQR(fp-fptt);
1.183     brouard  2777: #endif
1.202     brouard  2778:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2779: #ifdef DEBUG
1.181     brouard  2780:       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);
                   2781:       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  2782:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2783:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2784:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2785:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2786:       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);
                   2787:       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);
                   2788: #endif
1.183     brouard  2789: #ifdef POWELLORIGINAL
                   2790:       if (t < 0.0) { /* Then we use it for new direction */
                   2791: #else
1.182     brouard  2792:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2793:                                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  2794:         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  2795:         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  2796:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2797:       } 
1.181     brouard  2798:       if (directest < 0.0) { /* Then we use it for new direction */
                   2799: #endif
1.191     brouard  2800: #ifdef DEBUGLINMIN
1.234     brouard  2801:        printf("Before linmin in direction P%d-P0\n",n);
                   2802:        for (j=1;j<=n;j++) {
                   2803:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2804:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2805:          if(j % ncovmodel == 0){
                   2806:            printf("\n");
                   2807:            fprintf(ficlog,"\n");
                   2808:          }
                   2809:        }
1.224     brouard  2810: #endif
                   2811: #ifdef LINMINORIGINAL
1.234     brouard  2812:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2813: #else
1.234     brouard  2814:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2815:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2816: #endif
1.234     brouard  2817:        
1.191     brouard  2818: #ifdef DEBUGLINMIN
1.234     brouard  2819:        for (j=1;j<=n;j++) { 
                   2820:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2821:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2822:          if(j % ncovmodel == 0){
                   2823:            printf("\n");
                   2824:            fprintf(ficlog,"\n");
                   2825:          }
                   2826:        }
1.224     brouard  2827: #endif
1.234     brouard  2828:        for (j=1;j<=n;j++) { 
                   2829:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2830:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2831:        }
1.224     brouard  2832: #ifdef LINMINORIGINAL
                   2833: #else
1.234     brouard  2834:        for (j=1, flatd=0;j<=n;j++) {
                   2835:          if(flatdir[j]>0)
                   2836:            flatd++;
                   2837:        }
                   2838:        if(flatd >0){
1.255     brouard  2839:          printf("%d flat directions: ",flatd);
                   2840:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2841:          for (j=1;j<=n;j++) { 
                   2842:            if(flatdir[j]>0){
                   2843:              printf("%d ",j);
                   2844:              fprintf(ficlog,"%d ",j);
                   2845:            }
                   2846:          }
                   2847:          printf("\n");
                   2848:          fprintf(ficlog,"\n");
1.319     brouard  2849: #ifdef FLATSUP
                   2850:           free_vector(xit,1,n); 
                   2851:           free_vector(xits,1,n); 
                   2852:           free_vector(ptt,1,n); 
                   2853:           free_vector(pt,1,n); 
                   2854:           return;
                   2855: #endif
1.234     brouard  2856:        }
1.191     brouard  2857: #endif
1.234     brouard  2858:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2859:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2860:        
1.126     brouard  2861: #ifdef DEBUG
1.234     brouard  2862:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2863:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2864:        for(j=1;j<=n;j++){
                   2865:          printf(" %lf",xit[j]);
                   2866:          fprintf(ficlog," %lf",xit[j]);
                   2867:        }
                   2868:        printf("\n");
                   2869:        fprintf(ficlog,"\n");
1.126     brouard  2870: #endif
1.192     brouard  2871:       } /* end of t or directest negative */
1.224     brouard  2872: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2873: #else
1.234     brouard  2874:       } /* end if (fptt < fp)  */
1.192     brouard  2875: #endif
1.225     brouard  2876: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2877:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2878: #else
1.224     brouard  2879: #endif
1.234     brouard  2880:                } /* loop iteration */ 
1.126     brouard  2881: } 
1.234     brouard  2882:   
1.126     brouard  2883: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2884:   
1.235     brouard  2885:   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  2886:   {
1.338     brouard  2887:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2888:      *   (and selected quantitative values in nres)
                   2889:      *  by left multiplying the unit
                   2890:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2891:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2892:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2893:      * or prevalence in state 1, prevalence in state 2, 0
                   2894:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2895:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2896:      * Output is prlim.
                   2897:      * Initial matrix pimij 
                   2898:      */
1.206     brouard  2899:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2900:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2901:   /*  0,                   0                  , 1} */
                   2902:   /*
                   2903:    * and after some iteration: */
                   2904:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2905:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2906:   /*  0,                   0                  , 1} */
                   2907:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2908:   /* {0.51571254859325999, 0.4842874514067399, */
                   2909:   /*  0.51326036147820708, 0.48673963852179264} */
                   2910:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2911:     
1.332     brouard  2912:     int i, ii,j,k, k1;
1.209     brouard  2913:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2914:   /* double **matprod2(); */ /* test */
1.218     brouard  2915:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2916:   double **newm;
1.209     brouard  2917:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2918:   int ncvloop=0;
1.288     brouard  2919:   int first=0;
1.169     brouard  2920:   
1.209     brouard  2921:   min=vector(1,nlstate);
                   2922:   max=vector(1,nlstate);
                   2923:   meandiff=vector(1,nlstate);
                   2924: 
1.218     brouard  2925:        /* Starting with matrix unity */
1.126     brouard  2926:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2927:     for (j=1;j<=nlstate+ndeath;j++){
                   2928:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2929:     }
1.169     brouard  2930:   
                   2931:   cov[1]=1.;
                   2932:   
                   2933:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2934:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2935:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2936:     ncvloop++;
1.126     brouard  2937:     newm=savm;
                   2938:     /* Covariates have to be included here again */
1.138     brouard  2939:     cov[2]=agefin;
1.319     brouard  2940:      if(nagesqr==1){
                   2941:       cov[3]= agefin*agefin;
                   2942:      }
1.332     brouard  2943:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2944:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2945:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2946:        if(Typevar[k1]==1){ /* A product with age */
                   2947:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2948:        }else{
                   2949:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2950:        }
                   2951:      }/* End of loop on model equation */
                   2952:      
                   2953: /* Start of old code (replaced by a loop on position in the model equation */
                   2954:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2955:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2956:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2957:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2958:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2959:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2960:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2961:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2962:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2963:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2964:     /*    *nsd=3                              (1)  (2)           (3) */
                   2965:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2966:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2967:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2968:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2969:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2970:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2971:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2972:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2973:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2974:     /*    *TvarsDpType */
                   2975:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2976:     /*    * nsd=1              (1)           (2) */
                   2977:     /*    *TvarsD[nsd]          3             2 */
                   2978:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2979:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2980:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2981:     /*    *\/ */
                   2982:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2983:     /*   /\* 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)); *\/ */
                   2984:     /* } */
                   2985:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2986:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2987:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2988:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2989:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2990:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2991:     /*   /\* 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]); *\/ */
                   2992:     /* } */
                   2993:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2994:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2995:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2996:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2997:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2998:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2999:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3000:     /*   } */
                   3001:     /*   /\* 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]); *\/ */
                   3002:     /* } */
                   3003:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3004:     /*   /\* 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]); *\/ */
                   3005:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3006:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3007:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3008:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3009:     /*         }else{ */
                   3010:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3011:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3012:     /*         } */
                   3013:     /*   }else{ */
                   3014:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3015:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3016:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3017:     /*         }else{ */
                   3018:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3019:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3020:     /*         } */
                   3021:     /*   } */
                   3022:     /* } /\* End product without age *\/ */
                   3023: /* ENd of old code */
1.138     brouard  3024:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3025:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3026:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3027:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3028:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3029:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3030:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3031:     
1.126     brouard  3032:     savm=oldm;
                   3033:     oldm=newm;
1.209     brouard  3034: 
                   3035:     for(j=1; j<=nlstate; j++){
                   3036:       max[j]=0.;
                   3037:       min[j]=1.;
                   3038:     }
                   3039:     for(i=1;i<=nlstate;i++){
                   3040:       sumnew=0;
                   3041:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3042:       for(j=1; j<=nlstate; j++){ 
                   3043:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3044:        max[j]=FMAX(max[j],prlim[i][j]);
                   3045:        min[j]=FMIN(min[j],prlim[i][j]);
                   3046:       }
                   3047:     }
                   3048: 
1.126     brouard  3049:     maxmax=0.;
1.209     brouard  3050:     for(j=1; j<=nlstate; j++){
                   3051:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3052:       maxmax=FMAX(maxmax,meandiff[j]);
                   3053:       /* 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  3054:     } /* j loop */
1.203     brouard  3055:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3056:     /* 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  3057:     if(maxmax < ftolpl){
1.209     brouard  3058:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3059:       free_vector(min,1,nlstate);
                   3060:       free_vector(max,1,nlstate);
                   3061:       free_vector(meandiff,1,nlstate);
1.126     brouard  3062:       return prlim;
                   3063:     }
1.288     brouard  3064:   } /* agefin loop */
1.208     brouard  3065:     /* After some age loop it doesn't converge */
1.288     brouard  3066:   if(!first){
                   3067:     first=1;
                   3068:     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  3069:     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);
                   3070:   }else if (first >=1 && first <10){
                   3071:     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);
                   3072:     first++;
                   3073:   }else if (first ==10){
                   3074:     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);
                   3075:     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");
                   3076:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3077:     first++;
1.288     brouard  3078:   }
                   3079: 
1.209     brouard  3080:   /* 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); */
                   3081:   free_vector(min,1,nlstate);
                   3082:   free_vector(max,1,nlstate);
                   3083:   free_vector(meandiff,1,nlstate);
1.208     brouard  3084:   
1.169     brouard  3085:   return prlim; /* should not reach here */
1.126     brouard  3086: }
                   3087: 
1.217     brouard  3088: 
                   3089:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3090: 
1.218     brouard  3091:  /* 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) */
                   3092:  /* 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  3093:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3094: {
1.264     brouard  3095:   /* 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  3096:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3097:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3098:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3099:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3100:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3101:   /* Initial matrix pimij */
                   3102:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3103:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3104:   /*  0,                   0                  , 1} */
                   3105:   /*
                   3106:    * and after some iteration: */
                   3107:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3108:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3109:   /*  0,                   0                  , 1} */
                   3110:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3111:   /* {0.51571254859325999, 0.4842874514067399, */
                   3112:   /*  0.51326036147820708, 0.48673963852179264} */
                   3113:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3114: 
1.332     brouard  3115:   int i, ii,j,k, k1;
1.247     brouard  3116:   int first=0;
1.217     brouard  3117:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3118:   /* double **matprod2(); */ /* test */
                   3119:   double **out, cov[NCOVMAX+1], **bmij();
                   3120:   double **newm;
1.218     brouard  3121:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3122:   double        **oldm, **savm;  /* for use */
                   3123: 
1.217     brouard  3124:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3125:   int ncvloop=0;
                   3126:   
                   3127:   min=vector(1,nlstate);
                   3128:   max=vector(1,nlstate);
                   3129:   meandiff=vector(1,nlstate);
                   3130: 
1.266     brouard  3131:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3132:   oldm=oldms; savm=savms;
                   3133:   
                   3134:   /* Starting with matrix unity */
                   3135:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3136:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3137:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3138:     }
                   3139:   
                   3140:   cov[1]=1.;
                   3141:   
                   3142:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3143:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3144:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3145:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3146:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3147:     ncvloop++;
1.218     brouard  3148:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3149:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3150:     /* Covariates have to be included here again */
                   3151:     cov[2]=agefin;
1.319     brouard  3152:     if(nagesqr==1){
1.217     brouard  3153:       cov[3]= agefin*agefin;;
1.319     brouard  3154:     }
1.332     brouard  3155:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3156:       if(Typevar[k1]==1){ /* A product with age */
                   3157:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3158:       }else{
1.332     brouard  3159:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3160:       }
1.332     brouard  3161:     }/* End of loop on model equation */
                   3162: 
                   3163: /* Old code */ 
                   3164: 
                   3165:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3166:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3167:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3168:     /*   /\* 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)); *\/ */
                   3169:     /* } */
                   3170:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3171:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3172:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3173:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3174:     /* /\* } *\/ */
                   3175:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3176:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3177:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3178:     /*   /\* 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]); *\/ */
                   3179:     /* } */
                   3180:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3181:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3182:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3183:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3184:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3185:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3186:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3187:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3188:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3189:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3190:     /*   } */
                   3191:     /*   /\* 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]); *\/ */
                   3192:     /* } */
                   3193:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3194:     /*   /\* 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]); *\/ */
                   3195:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3196:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3197:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3198:     /*         }else{ */
                   3199:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3200:     /*         } */
                   3201:     /*   }else{ */
                   3202:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3203:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3204:     /*         }else{ */
                   3205:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3206:     /*         } */
                   3207:     /*   } */
                   3208:     /* } */
1.217     brouard  3209:     
                   3210:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3211:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3212:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3213:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3214:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3215:                /* ij should be linked to the correct index of cov */
                   3216:                /* age and covariate values ij are in 'cov', but we need to pass
                   3217:                 * ij for the observed prevalence at age and status and covariate
                   3218:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3219:                 */
                   3220:     /* 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 *\/ */
                   3221:     /* 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 *\/ */
                   3222:     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  3223:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3224:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3225:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3226:     /*         printf("%d newm= ",i); */
                   3227:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3228:     /*           printf("%f ",newm[i][j]); */
                   3229:     /*         } */
                   3230:     /*         printf("oldm * "); */
                   3231:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3232:     /*           printf("%f ",oldm[i][j]); */
                   3233:     /*         } */
1.268     brouard  3234:     /*         printf(" bmmij "); */
1.266     brouard  3235:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3236:     /*           printf("%f ",pmmij[i][j]); */
                   3237:     /*         } */
                   3238:     /*         printf("\n"); */
                   3239:     /*   } */
                   3240:     /* } */
1.217     brouard  3241:     savm=oldm;
                   3242:     oldm=newm;
1.266     brouard  3243: 
1.217     brouard  3244:     for(j=1; j<=nlstate; j++){
                   3245:       max[j]=0.;
                   3246:       min[j]=1.;
                   3247:     }
                   3248:     for(j=1; j<=nlstate; j++){ 
                   3249:       for(i=1;i<=nlstate;i++){
1.234     brouard  3250:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3251:        bprlim[i][j]= newm[i][j];
                   3252:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3253:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3254:       }
                   3255:     }
1.218     brouard  3256:                
1.217     brouard  3257:     maxmax=0.;
                   3258:     for(i=1; i<=nlstate; i++){
1.318     brouard  3259:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3260:       maxmax=FMAX(maxmax,meandiff[i]);
                   3261:       /* 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  3262:     } /* i loop */
1.217     brouard  3263:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3264:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3265:     if(maxmax < ftolpl){
1.220     brouard  3266:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3267:       free_vector(min,1,nlstate);
                   3268:       free_vector(max,1,nlstate);
                   3269:       free_vector(meandiff,1,nlstate);
                   3270:       return bprlim;
                   3271:     }
1.288     brouard  3272:   } /* agefin loop */
1.217     brouard  3273:     /* After some age loop it doesn't converge */
1.288     brouard  3274:   if(!first){
1.247     brouard  3275:     first=1;
                   3276:     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\
                   3277: 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);
                   3278:   }
                   3279:   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  3280: 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);
                   3281:   /* 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); */
                   3282:   free_vector(min,1,nlstate);
                   3283:   free_vector(max,1,nlstate);
                   3284:   free_vector(meandiff,1,nlstate);
                   3285:   
                   3286:   return bprlim; /* should not reach here */
                   3287: }
                   3288: 
1.126     brouard  3289: /*************** transition probabilities ***************/ 
                   3290: 
                   3291: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3292: {
1.138     brouard  3293:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3294:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3295:      model to the ncovmodel covariates (including constant and age).
                   3296:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3297:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3298:      ncth covariate in the global vector x is given by the formula:
                   3299:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3300:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3301:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3302:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3303:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3304:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3305:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3306:   */
                   3307:   double s1, lnpijopii;
1.126     brouard  3308:   /*double t34;*/
1.164     brouard  3309:   int i,j, nc, ii, jj;
1.126     brouard  3310: 
1.223     brouard  3311:   for(i=1; i<= nlstate; i++){
                   3312:     for(j=1; j<i;j++){
                   3313:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3314:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3315:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3316:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3317:       }
                   3318:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3319:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3320:     }
                   3321:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3322:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3323:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3324:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3325:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3326:       }
                   3327:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3328:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3329:     }
                   3330:   }
1.218     brouard  3331:   
1.223     brouard  3332:   for(i=1; i<= nlstate; i++){
                   3333:     s1=0;
                   3334:     for(j=1; j<i; j++){
1.339     brouard  3335:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3336:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3337:     }
                   3338:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3339:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3340:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3341:     }
                   3342:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3343:     ps[i][i]=1./(s1+1.);
                   3344:     /* Computing other pijs */
                   3345:     for(j=1; j<i; j++)
1.325     brouard  3346:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3347:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3348:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3349:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3350:   } /* end i */
1.218     brouard  3351:   
1.223     brouard  3352:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3353:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3354:       ps[ii][jj]=0;
                   3355:       ps[ii][ii]=1;
                   3356:     }
                   3357:   }
1.294     brouard  3358: 
                   3359: 
1.223     brouard  3360:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3361:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3362:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3363:   /*   } */
                   3364:   /*   printf("\n "); */
                   3365:   /* } */
                   3366:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3367:   /*
                   3368:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3369:                goto end;*/
1.266     brouard  3370:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3371: }
                   3372: 
1.218     brouard  3373: /*************** backward transition probabilities ***************/ 
                   3374: 
                   3375:  /* 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 ) */
                   3376: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3377:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3378: {
1.302     brouard  3379:   /* 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  3380:    * 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  3381:    */
1.218     brouard  3382:   int i, ii, j,k;
1.222     brouard  3383:   
                   3384:   double **out, **pmij();
                   3385:   double sumnew=0.;
1.218     brouard  3386:   double agefin;
1.292     brouard  3387:   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  3388:   double **dnewm, **dsavm, **doldm;
                   3389:   double **bbmij;
                   3390:   
1.218     brouard  3391:   doldm=ddoldms; /* global pointers */
1.222     brouard  3392:   dnewm=ddnewms;
                   3393:   dsavm=ddsavms;
1.318     brouard  3394: 
                   3395:   /* Debug */
                   3396:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3397:   agefin=cov[2];
1.268     brouard  3398:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3399:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3400:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3401:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3402: 
                   3403:   /* P_x */
1.325     brouard  3404:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3405:   /* outputs pmmij which is a stochastic matrix in row */
                   3406: 
                   3407:   /* Diag(w_x) */
1.292     brouard  3408:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3409:   sumnew=0.;
1.269     brouard  3410:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3411:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3412:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3413:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3414:   }
                   3415:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3416:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3417:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3418:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3419:     }
                   3420:   }else{
                   3421:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3422:       for (j=1;j<=nlstate+ndeath;j++)
                   3423:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3424:     }
                   3425:     /* if(sumnew <0.9){ */
                   3426:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3427:     /* } */
                   3428:   }
                   3429:   k3=0.0;  /* We put the last diagonal to 0 */
                   3430:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3431:       doldm[ii][ii]= k3;
                   3432:   }
                   3433:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3434:   
1.292     brouard  3435:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3436:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3437: 
1.292     brouard  3438:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3439:   /* 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  3440:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3441:     sumnew=0.;
1.222     brouard  3442:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3443:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3444:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3445:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3446:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3447:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3448:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3449:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3450:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3451:        /* }else */
1.268     brouard  3452:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3453:     } /*End ii */
                   3454:   } /* 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 */
                   3455: 
1.292     brouard  3456:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3457:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3458:   /* end bmij */
1.266     brouard  3459:   return ps; /*pointer is unchanged */
1.218     brouard  3460: }
1.217     brouard  3461: /*************** transition probabilities ***************/ 
                   3462: 
1.218     brouard  3463: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3464: {
                   3465:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3466:      computes the probability to be observed in state j being in state i by appying the
                   3467:      model to the ncovmodel covariates (including constant and age).
                   3468:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3469:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3470:      ncth covariate in the global vector x is given by the formula:
                   3471:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3472:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3473:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3474:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3475:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3476:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3477:   */
                   3478:   double s1, lnpijopii;
                   3479:   /*double t34;*/
                   3480:   int i,j, nc, ii, jj;
                   3481: 
1.234     brouard  3482:   for(i=1; i<= nlstate; i++){
                   3483:     for(j=1; j<i;j++){
                   3484:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3485:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3486:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3487:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3488:       }
                   3489:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3490:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3491:     }
                   3492:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3493:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3494:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3495:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3496:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3497:       }
                   3498:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3499:     }
                   3500:   }
                   3501:   
                   3502:   for(i=1; i<= nlstate; i++){
                   3503:     s1=0;
                   3504:     for(j=1; j<i; j++){
                   3505:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3506:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3507:     }
                   3508:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3509:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3510:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3511:     }
                   3512:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3513:     ps[i][i]=1./(s1+1.);
                   3514:     /* Computing other pijs */
                   3515:     for(j=1; j<i; j++)
                   3516:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3517:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3518:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3519:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3520:   } /* end i */
                   3521:   
                   3522:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3523:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3524:       ps[ii][jj]=0;
                   3525:       ps[ii][ii]=1;
                   3526:     }
                   3527:   }
1.296     brouard  3528:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3529:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3530:     s1=0.;
                   3531:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3532:       s1+=ps[ii][jj];
                   3533:     }
                   3534:     for(ii=1; ii<= nlstate; ii++){
                   3535:       ps[ii][jj]=ps[ii][jj]/s1;
                   3536:     }
                   3537:   }
                   3538:   /* Transposition */
                   3539:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3540:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3541:       s1=ps[ii][jj];
                   3542:       ps[ii][jj]=ps[jj][ii];
                   3543:       ps[jj][ii]=s1;
                   3544:     }
                   3545:   }
                   3546:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3547:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3548:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3549:   /*   } */
                   3550:   /*   printf("\n "); */
                   3551:   /* } */
                   3552:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3553:   /*
                   3554:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3555:     goto end;*/
                   3556:   return ps;
1.217     brouard  3557: }
                   3558: 
                   3559: 
1.126     brouard  3560: /**************** Product of 2 matrices ******************/
                   3561: 
1.145     brouard  3562: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3563: {
                   3564:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3565:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3566:   /* in, b, out are matrice of pointers which should have been initialized 
                   3567:      before: only the contents of out is modified. The function returns
                   3568:      a pointer to pointers identical to out */
1.145     brouard  3569:   int i, j, k;
1.126     brouard  3570:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3571:     for(k=ncolol; k<=ncoloh; k++){
                   3572:       out[i][k]=0.;
                   3573:       for(j=ncl; j<=nch; j++)
                   3574:        out[i][k] +=in[i][j]*b[j][k];
                   3575:     }
1.126     brouard  3576:   return out;
                   3577: }
                   3578: 
                   3579: 
                   3580: /************* Higher Matrix Product ***************/
                   3581: 
1.235     brouard  3582: 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  3583: {
1.336     brouard  3584:   /* Already optimized with precov.
                   3585:      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  3586:      'nhstepm*hstepm*stepm' months (i.e. until
                   3587:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3588:      nhstepm*hstepm matrices. 
                   3589:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3590:      (typically every 2 years instead of every month which is too big 
                   3591:      for the memory).
                   3592:      Model is determined by parameters x and covariates have to be 
                   3593:      included manually here. 
                   3594: 
                   3595:      */
                   3596: 
1.330     brouard  3597:   int i, j, d, h, k, k1;
1.131     brouard  3598:   double **out, cov[NCOVMAX+1];
1.126     brouard  3599:   double **newm;
1.187     brouard  3600:   double agexact;
1.214     brouard  3601:   double agebegin, ageend;
1.126     brouard  3602: 
                   3603:   /* Hstepm could be zero and should return the unit matrix */
                   3604:   for (i=1;i<=nlstate+ndeath;i++)
                   3605:     for (j=1;j<=nlstate+ndeath;j++){
                   3606:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3607:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3608:     }
                   3609:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3610:   for(h=1; h <=nhstepm; h++){
                   3611:     for(d=1; d <=hstepm; d++){
                   3612:       newm=savm;
                   3613:       /* Covariates have to be included here again */
                   3614:       cov[1]=1.;
1.214     brouard  3615:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3616:       cov[2]=agexact;
1.319     brouard  3617:       if(nagesqr==1){
1.227     brouard  3618:        cov[3]= agexact*agexact;
1.319     brouard  3619:       }
1.330     brouard  3620:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3621:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3622:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3623:        if(Typevar[k1]==1){ /* A product with age */
                   3624:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3625:        }else{
                   3626:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3627:        }
                   3628:       }/* End of loop on model equation */
                   3629:        /* Old code */ 
                   3630: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3631: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3632: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3633: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3634: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3635: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3636: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3637: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3638: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3639: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3640: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3641: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3642: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3643: /*       /\* 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]])); *\/ */
                   3644: /*       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); */
                   3645: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3646: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3647: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3648: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3649: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3650: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3651: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3652: /*       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]]); */
                   3653: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3654: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3655: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3656: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3657: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3658: /*       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]); */
                   3659: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3660: 
                   3661: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3662: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3663: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3664: /*       /\* *\/ */
1.330     brouard  3665: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3666: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3667: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3668: /* /\*cptcovage=2                   1               2      *\/ */
                   3669: /* /\*Tage[k]=                      5               8      *\/  */
                   3670: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3671: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3672: /*       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]]); */
                   3673: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3674: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3675: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3676: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3677: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3678: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3679: /*       /\*   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); *\/ */
                   3680: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3681: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3682: /*       /\* } *\/ */
                   3683: /*       /\* 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]); *\/ */
                   3684: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3685: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3686: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3687: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3688: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3689: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3690: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3691: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3692: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3693:          
1.332     brouard  3694: /*       /\* 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])]); *\/ */
                   3695: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3696: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3697: /*       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]]); */
                   3698: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3699: 
                   3700: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3701: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3702: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3703: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3704: /*           /\* 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]])]; *\/ */
                   3705: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3706: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3707: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3708: /*       /\*   } *\/ */
                   3709: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3710: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3711: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3712: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3713: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3714: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3715: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3716: /*       /\*   } *\/ */
                   3717: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3718: /*     }/\*end of products *\/ */
                   3719:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3720:       /* for (k=1; k<=cptcovn;k++)  */
                   3721:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3722:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3723:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3724:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3725:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3726:       
                   3727:       
1.126     brouard  3728:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3729:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3730:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3731:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3732:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3733:       /* if((int)age == 70){ */
                   3734:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3735:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3736:       /*         printf("%d pmmij ",i); */
                   3737:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3738:       /*           printf("%f ",pmmij[i][j]); */
                   3739:       /*         } */
                   3740:       /*         printf(" oldm "); */
                   3741:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3742:       /*           printf("%f ",oldm[i][j]); */
                   3743:       /*         } */
                   3744:       /*         printf("\n"); */
                   3745:       /*       } */
                   3746:       /* } */
1.126     brouard  3747:       savm=oldm;
                   3748:       oldm=newm;
                   3749:     }
                   3750:     for(i=1; i<=nlstate+ndeath; i++)
                   3751:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3752:        po[i][j][h]=newm[i][j];
                   3753:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3754:       }
1.128     brouard  3755:     /*printf("h=%d ",h);*/
1.126     brouard  3756:   } /* end h */
1.267     brouard  3757:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3758:   return po;
                   3759: }
                   3760: 
1.217     brouard  3761: /************* Higher Back Matrix Product ***************/
1.218     brouard  3762: /* 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  3763: 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  3764: {
1.332     brouard  3765:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3766:      computes the transition matrix starting at age 'age' over
1.217     brouard  3767:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3768:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3769:      nhstepm*hstepm matrices.
                   3770:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3771:      (typically every 2 years instead of every month which is too big
1.217     brouard  3772:      for the memory).
1.218     brouard  3773:      Model is determined by parameters x and covariates have to be
1.266     brouard  3774:      included manually here. Then we use a call to bmij(x and cov)
                   3775:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3776:   */
1.217     brouard  3777: 
1.332     brouard  3778:   int i, j, d, h, k, k1;
1.266     brouard  3779:   double **out, cov[NCOVMAX+1], **bmij();
                   3780:   double **newm, ***newmm;
1.217     brouard  3781:   double agexact;
                   3782:   double agebegin, ageend;
1.222     brouard  3783:   double **oldm, **savm;
1.217     brouard  3784: 
1.266     brouard  3785:   newmm=po; /* To be saved */
                   3786:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3787:   /* Hstepm could be zero and should return the unit matrix */
                   3788:   for (i=1;i<=nlstate+ndeath;i++)
                   3789:     for (j=1;j<=nlstate+ndeath;j++){
                   3790:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3791:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3792:     }
                   3793:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3794:   for(h=1; h <=nhstepm; h++){
                   3795:     for(d=1; d <=hstepm; d++){
                   3796:       newm=savm;
                   3797:       /* Covariates have to be included here again */
                   3798:       cov[1]=1.;
1.271     brouard  3799:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3800:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3801:         /* Debug */
                   3802:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3803:       cov[2]=agexact;
1.332     brouard  3804:       if(nagesqr==1){
1.222     brouard  3805:        cov[3]= agexact*agexact;
1.332     brouard  3806:       }
                   3807:       /** New code */
                   3808:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3809:        if(Typevar[k1]==1){ /* A product with age */
                   3810:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3811:        }else{
1.332     brouard  3812:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3813:        }
1.332     brouard  3814:       }/* End of loop on model equation */
                   3815:       /** End of new code */
                   3816:   /** This was old code */
                   3817:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3818:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3819:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3820:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3821:       /*   /\* 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)); *\/ */
                   3822:       /* } */
                   3823:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3824:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3825:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3826:       /*       /\* 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]); *\/ */
                   3827:       /* } */
                   3828:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3829:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3830:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3831:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3832:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3833:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3834:       /*       } */
                   3835:       /*       /\* 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]); *\/ */
                   3836:       /* } */
                   3837:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3838:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3839:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3840:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3841:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3842:       /*         }else{ */
                   3843:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3844:       /*         } */
                   3845:       /*       }else{ */
                   3846:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3847:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3848:       /*         }else{ */
                   3849:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3850:       /*         } */
                   3851:       /*       } */
                   3852:       /* }                      */
                   3853:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3854:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3855: /** End of old code */
                   3856:       
1.218     brouard  3857:       /* Careful transposed matrix */
1.266     brouard  3858:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3859:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3860:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3861:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3862:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3863:       /* if((int)age == 70){ */
                   3864:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3865:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3866:       /*         printf("%d pmmij ",i); */
                   3867:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3868:       /*           printf("%f ",pmmij[i][j]); */
                   3869:       /*         } */
                   3870:       /*         printf(" oldm "); */
                   3871:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3872:       /*           printf("%f ",oldm[i][j]); */
                   3873:       /*         } */
                   3874:       /*         printf("\n"); */
                   3875:       /*       } */
                   3876:       /* } */
                   3877:       savm=oldm;
                   3878:       oldm=newm;
                   3879:     }
                   3880:     for(i=1; i<=nlstate+ndeath; i++)
                   3881:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3882:        po[i][j][h]=newm[i][j];
1.268     brouard  3883:        /* if(h==nhstepm) */
                   3884:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3885:       }
1.268     brouard  3886:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3887:   } /* end h */
1.268     brouard  3888:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3889:   return po;
                   3890: }
                   3891: 
                   3892: 
1.162     brouard  3893: #ifdef NLOPT
                   3894:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3895:   double fret;
                   3896:   double *xt;
                   3897:   int j;
                   3898:   myfunc_data *d2 = (myfunc_data *) pd;
                   3899: /* xt = (p1-1); */
                   3900:   xt=vector(1,n); 
                   3901:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3902: 
                   3903:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3904:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3905:   printf("Function = %.12lf ",fret);
                   3906:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3907:   printf("\n");
                   3908:  free_vector(xt,1,n);
                   3909:   return fret;
                   3910: }
                   3911: #endif
1.126     brouard  3912: 
                   3913: /*************** log-likelihood *************/
                   3914: double func( double *x)
                   3915: {
1.336     brouard  3916:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3917:   int ioffset=0;
1.339     brouard  3918:   int ipos=0,iposold=0,ncovv=0;
                   3919: 
1.340     brouard  3920:   double cotvarv, cotvarvold;
1.226     brouard  3921:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3922:   double **out;
                   3923:   double lli; /* Individual log likelihood */
                   3924:   int s1, s2;
1.228     brouard  3925:   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  3926: 
1.226     brouard  3927:   double bbh, survp;
                   3928:   double agexact;
1.336     brouard  3929:   double agebegin, ageend;
1.226     brouard  3930:   /*extern weight */
                   3931:   /* We are differentiating ll according to initial status */
                   3932:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3933:   /*for(i=1;i<imx;i++) 
                   3934:     printf(" %d\n",s[4][i]);
                   3935:   */
1.162     brouard  3936: 
1.226     brouard  3937:   ++countcallfunc;
1.162     brouard  3938: 
1.226     brouard  3939:   cov[1]=1.;
1.126     brouard  3940: 
1.226     brouard  3941:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3942:   ioffset=0;
1.226     brouard  3943:   if(mle==1){
                   3944:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3945:       /* Computes the values of the ncovmodel covariates of the model
                   3946:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3947:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3948:         to be observed in j being in i according to the model.
                   3949:       */
1.243     brouard  3950:       ioffset=2+nagesqr ;
1.233     brouard  3951:    /* Fixed */
1.345   ! brouard  3952:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  3953:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3954:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3955:        /*  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  3956:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3957:        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  3958:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3959:       }
1.226     brouard  3960:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3961:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3962:         has been calculated etc */
                   3963:       /* For an individual i, wav[i] gives the number of effective waves */
                   3964:       /* We compute the contribution to Likelihood of each effective transition
                   3965:         mw[mi][i] is real wave of the mi th effectve wave */
                   3966:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3967:         s2=s[mw[mi+1][i]][i];
1.341     brouard  3968:         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  3969:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3970:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3971:       */
1.336     brouard  3972:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3973:       /* Wave varying (but not age varying) */
1.339     brouard  3974:        /* 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*\/ */
                   3975:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3976:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3977:        /* } */
1.340     brouard  3978:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3979:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3980:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345   ! brouard  3981:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  3982:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3983:          }else{ /* fixed covariate */
1.345   ! brouard  3984:            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  3985:          }
1.339     brouard  3986:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3987:            cotvarvold=cotvarv;
                   3988:          }else{ /* A second product */
                   3989:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3990:          }
                   3991:          iposold=ipos;
1.340     brouard  3992:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  3993:        }
1.339     brouard  3994:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   3995:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3996:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3997:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3998:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3999:        /*   printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
                   4000:        /* } */
                   4001:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   4002:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4003:        /*   /\* 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]); *\/ */
                   4004:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   4005:        /* } */
                   4006:        /* for products of time varying to be done */
1.234     brouard  4007:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4008:          for (j=1;j<=nlstate+ndeath;j++){
                   4009:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4010:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4011:          }
1.336     brouard  4012: 
                   4013:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4014:        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  4015:        for(d=0; d<dh[mi][i]; d++){
                   4016:          newm=savm;
                   4017:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4018:          cov[2]=agexact;
                   4019:          if(nagesqr==1)
                   4020:            cov[3]= agexact*agexact;  /* Should be changed here */
                   4021:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  4022:            if(!FixedV[Tvar[Tage[kk]]])
                   4023:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4024:            else
1.341     brouard  4025:              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.234     brouard  4026:          }
                   4027:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4028:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4029:          savm=oldm;
                   4030:          oldm=newm;
                   4031:        } /* end mult */
                   4032:        
                   4033:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4034:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4035:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4036:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4037:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4038:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4039:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4040:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4041:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4042:                                 * -stepm/2 to stepm/2 .
                   4043:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4044:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4045:                                 */
1.234     brouard  4046:        s1=s[mw[mi][i]][i];
                   4047:        s2=s[mw[mi+1][i]][i];
                   4048:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4049:        /* bias bh is positive if real duration
                   4050:         * is higher than the multiple of stepm and negative otherwise.
                   4051:         */
                   4052:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4053:        if( s2 > nlstate){ 
                   4054:          /* i.e. if s2 is a death state and if the date of death is known 
                   4055:             then the contribution to the likelihood is the probability to 
                   4056:             die between last step unit time and current  step unit time, 
                   4057:             which is also equal to probability to die before dh 
                   4058:             minus probability to die before dh-stepm . 
                   4059:             In version up to 0.92 likelihood was computed
                   4060:             as if date of death was unknown. Death was treated as any other
                   4061:             health state: the date of the interview describes the actual state
                   4062:             and not the date of a change in health state. The former idea was
                   4063:             to consider that at each interview the state was recorded
                   4064:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4065:             introduced the exact date of death then we should have modified
                   4066:             the contribution of an exact death to the likelihood. This new
                   4067:             contribution is smaller and very dependent of the step unit
                   4068:             stepm. It is no more the probability to die between last interview
                   4069:             and month of death but the probability to survive from last
                   4070:             interview up to one month before death multiplied by the
                   4071:             probability to die within a month. Thanks to Chris
                   4072:             Jackson for correcting this bug.  Former versions increased
                   4073:             mortality artificially. The bad side is that we add another loop
                   4074:             which slows down the processing. The difference can be up to 10%
                   4075:             lower mortality.
                   4076:          */
                   4077:          /* If, at the beginning of the maximization mostly, the
                   4078:             cumulative probability or probability to be dead is
                   4079:             constant (ie = 1) over time d, the difference is equal to
                   4080:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4081:             s1 at precedent wave, to be dead a month before current
                   4082:             wave is equal to probability, being at state s1 at
                   4083:             precedent wave, to be dead at mont of the current
                   4084:             wave. Then the observed probability (that this person died)
                   4085:             is null according to current estimated parameter. In fact,
                   4086:             it should be very low but not zero otherwise the log go to
                   4087:             infinity.
                   4088:          */
1.183     brouard  4089: /* #ifdef INFINITYORIGINAL */
                   4090: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4091: /* #else */
                   4092: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4093: /*         lli=log(mytinydouble); */
                   4094: /*       else */
                   4095: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4096: /* #endif */
1.226     brouard  4097:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4098:          
1.226     brouard  4099:        } else if  ( s2==-1 ) { /* alive */
                   4100:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4101:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4102:          /*survp += out[s1][j]; */
                   4103:          lli= log(survp);
                   4104:        }
1.336     brouard  4105:        /* else if  (s2==-4) {  */
                   4106:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4107:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4108:        /*   lli= log(survp);  */
                   4109:        /* }  */
                   4110:        /* else if  (s2==-5) {  */
                   4111:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4112:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4113:        /*   lli= log(survp);  */
                   4114:        /* }  */
1.226     brouard  4115:        else{
                   4116:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4117:          /*  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 */
                   4118:        } 
                   4119:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4120:        /*if(lli ==000.0)*/
1.340     brouard  4121:        /* 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  4122:        ipmx +=1;
                   4123:        sw += weight[i];
                   4124:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4125:        /* if (lli < log(mytinydouble)){ */
                   4126:        /*   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); */
                   4127:        /*   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]); */
                   4128:        /* } */
                   4129:       } /* end of wave */
                   4130:     } /* end of individual */
                   4131:   }  else if(mle==2){
                   4132:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4133:       ioffset=2+nagesqr ;
                   4134:       for (k=1; k<=ncovf;k++)
                   4135:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4136:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4137:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4138:          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  4139:        }
1.226     brouard  4140:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4141:          for (j=1;j<=nlstate+ndeath;j++){
                   4142:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4143:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4144:          }
                   4145:        for(d=0; d<=dh[mi][i]; d++){
                   4146:          newm=savm;
                   4147:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4148:          cov[2]=agexact;
                   4149:          if(nagesqr==1)
                   4150:            cov[3]= agexact*agexact;
                   4151:          for (kk=1; kk<=cptcovage;kk++) {
                   4152:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4153:          }
                   4154:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4155:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4156:          savm=oldm;
                   4157:          oldm=newm;
                   4158:        } /* end mult */
                   4159:       
                   4160:        s1=s[mw[mi][i]][i];
                   4161:        s2=s[mw[mi+1][i]][i];
                   4162:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4163:        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 */
                   4164:        ipmx +=1;
                   4165:        sw += weight[i];
                   4166:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4167:       } /* end of wave */
                   4168:     } /* end of individual */
                   4169:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4170:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4171:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4172:       for(mi=1; mi<= wav[i]-1; mi++){
                   4173:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4174:          for (j=1;j<=nlstate+ndeath;j++){
                   4175:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4176:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4177:          }
                   4178:        for(d=0; d<dh[mi][i]; d++){
                   4179:          newm=savm;
                   4180:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4181:          cov[2]=agexact;
                   4182:          if(nagesqr==1)
                   4183:            cov[3]= agexact*agexact;
                   4184:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4185:            if(!FixedV[Tvar[Tage[kk]]])
                   4186:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4187:            else
1.341     brouard  4188:              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  4189:          }
                   4190:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4191:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4192:          savm=oldm;
                   4193:          oldm=newm;
                   4194:        } /* end mult */
                   4195:       
                   4196:        s1=s[mw[mi][i]][i];
                   4197:        s2=s[mw[mi+1][i]][i];
                   4198:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4199:        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 */
                   4200:        ipmx +=1;
                   4201:        sw += weight[i];
                   4202:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4203:       } /* end of wave */
                   4204:     } /* end of individual */
                   4205:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4206:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4207:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4208:       for(mi=1; mi<= wav[i]-1; mi++){
                   4209:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4210:          for (j=1;j<=nlstate+ndeath;j++){
                   4211:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4212:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4213:          }
                   4214:        for(d=0; d<dh[mi][i]; d++){
                   4215:          newm=savm;
                   4216:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4217:          cov[2]=agexact;
                   4218:          if(nagesqr==1)
                   4219:            cov[3]= agexact*agexact;
                   4220:          for (kk=1; kk<=cptcovage;kk++) {
                   4221:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4222:          }
1.126     brouard  4223:        
1.226     brouard  4224:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4225:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4226:          savm=oldm;
                   4227:          oldm=newm;
                   4228:        } /* end mult */
                   4229:       
                   4230:        s1=s[mw[mi][i]][i];
                   4231:        s2=s[mw[mi+1][i]][i];
                   4232:        if( s2 > nlstate){ 
                   4233:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4234:        } else if  ( s2==-1 ) { /* alive */
                   4235:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4236:            survp += out[s1][j];
                   4237:          lli= log(survp);
                   4238:        }else{
                   4239:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4240:        }
                   4241:        ipmx +=1;
                   4242:        sw += weight[i];
                   4243:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4244:        /* 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  4245:       } /* end of wave */
                   4246:     } /* end of individual */
                   4247:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4248:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4249:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4250:       for(mi=1; mi<= wav[i]-1; mi++){
                   4251:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4252:          for (j=1;j<=nlstate+ndeath;j++){
                   4253:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4254:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4255:          }
                   4256:        for(d=0; d<dh[mi][i]; d++){
                   4257:          newm=savm;
                   4258:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4259:          cov[2]=agexact;
                   4260:          if(nagesqr==1)
                   4261:            cov[3]= agexact*agexact;
                   4262:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4263:            if(!FixedV[Tvar[Tage[kk]]])
                   4264:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4265:            else
1.341     brouard  4266:              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  4267:          }
1.126     brouard  4268:        
1.226     brouard  4269:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4270:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4271:          savm=oldm;
                   4272:          oldm=newm;
                   4273:        } /* end mult */
                   4274:       
                   4275:        s1=s[mw[mi][i]][i];
                   4276:        s2=s[mw[mi+1][i]][i];
                   4277:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4278:        ipmx +=1;
                   4279:        sw += weight[i];
                   4280:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4281:        /*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]);*/
                   4282:       } /* end of wave */
                   4283:     } /* end of individual */
                   4284:   } /* End of if */
                   4285:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4286:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4287:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4288:   return -l;
1.126     brouard  4289: }
                   4290: 
                   4291: /*************** log-likelihood *************/
                   4292: double funcone( double *x)
                   4293: {
1.228     brouard  4294:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4295:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4296:   int ioffset=0;
1.339     brouard  4297:   int ipos=0,iposold=0,ncovv=0;
                   4298: 
1.340     brouard  4299:   double cotvarv, cotvarvold;
1.131     brouard  4300:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4301:   double **out;
                   4302:   double lli; /* Individual log likelihood */
                   4303:   double llt;
                   4304:   int s1, s2;
1.228     brouard  4305:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4306: 
1.126     brouard  4307:   double bbh, survp;
1.187     brouard  4308:   double agexact;
1.214     brouard  4309:   double agebegin, ageend;
1.126     brouard  4310:   /*extern weight */
                   4311:   /* We are differentiating ll according to initial status */
                   4312:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4313:   /*for(i=1;i<imx;i++) 
                   4314:     printf(" %d\n",s[4][i]);
                   4315:   */
                   4316:   cov[1]=1.;
                   4317: 
                   4318:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4319:   ioffset=0;
                   4320:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4321:     /* Computes the values of the ncovmodel covariates of the model
                   4322:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4323:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4324:        to be observed in j being in i according to the model.
                   4325:     */
1.243     brouard  4326:     /* ioffset=2+nagesqr+cptcovage; */
                   4327:     ioffset=2+nagesqr;
1.232     brouard  4328:     /* Fixed */
1.224     brouard  4329:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4330:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4331:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  4332:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4333:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4334:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4335:       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  4336: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4337: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4338: /*    cov[2+6]=covar[2][i]; V2  */
                   4339: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4340: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4341: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4342: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4343: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4344: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4345:     }
1.336     brouard  4346:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4347:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4348:         has been calculated etc */
                   4349:       /* For an individual i, wav[i] gives the number of effective waves */
                   4350:       /* We compute the contribution to Likelihood of each effective transition
                   4351:         mw[mi][i] is real wave of the mi th effectve wave */
                   4352:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4353:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4354:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4355:       */
                   4356:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4357:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4358:     /*   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?)*\/ */
                   4359:     /* } */
1.231     brouard  4360:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4361:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4362:     /* } */
1.225     brouard  4363:     
1.233     brouard  4364: 
                   4365:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4366:       /* 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 */
                   4367:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4368:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4369:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4370:       /* } */
                   4371:       
                   4372:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4373:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4374:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4375:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4376:       /* We need the position of the time varying or product in the model */
                   4377:       /* 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 */            
                   4378:       /* TvarVV gives the variable name */
1.340     brouard  4379:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4380:       *      k=         1   2     3     4         5        6        7       8        9
                   4381:       *  varying            1     2                                 3       4        5
                   4382:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4383:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4384:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4385:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4386:       */
1.345   ! brouard  4387:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
        !          4388:        /* 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[4]=6
        !          4389:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
        !          4390:        *             V1  V2     V3    V4   V5 V6     V7  V8
        !          4391:        *             0   0      0      0    0  1      1   1 
        !          4392:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4
        !          4393:        * kmodel           1     2      3      4      5        6         7         8         9        10        11
        !          4394:        * ncovf            1     2      3
        !          4395:        * ncovvt=14                            1      2       3 4       5 6       7 8       9 10     11 12     13 14
        !          4396:        * TvarVV[1]@14 = itv                   {6,     7,     6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
        !          4397:        * TvarVVind[1]@14=                    {4,     5,      6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
        !          4398:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
        !          4399:        * Tvar[1]@20=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14}
        !          4400:        * TvarFind[itv]                        0      0       0
        !          4401:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
        !          4402:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
        !          4403:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
        !          4404:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
        !          4405:        *   fixed covar[itv]                  [6]     [7]    [6][2]                            
        !          4406:        */
        !          4407: 
1.340     brouard  4408:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
1.345   ! brouard  4409:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product  */
1.340     brouard  4410:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345   ! brouard  4411:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
        !          4412:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
        !          4413:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4414:        }else{ /* fixed covariate */
1.345   ! brouard  4415:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
        !          4416:          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  4417:        }
1.339     brouard  4418:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4419:          cotvarvold=cotvarv;
                   4420:        }else{ /* A second product */
                   4421:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4422:        }
                   4423:        iposold=ipos;
1.340     brouard  4424:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4425:        /* For products */
                   4426:       }
                   4427:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4428:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4429:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4430:       /*       /\*           1  2   3      4      5                         *\/ */
                   4431:       /*       /\*itv           1                                           *\/ */
                   4432:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4433:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4434:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4435:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4436:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4437:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4438:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4439:       /*       /\* 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]); *\/ */
                   4440:       /* } */
1.232     brouard  4441:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4442:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4443:       /*       /\* 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]); *\/ */
                   4444:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4445:       /* } */
1.126     brouard  4446:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4447:        for (j=1;j<=nlstate+ndeath;j++){
                   4448:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4449:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4450:        }
1.214     brouard  4451:       
                   4452:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4453:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4454:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4455:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4456:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4457:          and mw[mi+1][i]. dh depends on stepm.*/
                   4458:        newm=savm;
1.247     brouard  4459:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4460:        cov[2]=agexact;
                   4461:        if(nagesqr==1)
                   4462:          cov[3]= agexact*agexact;
                   4463:        for (kk=1; kk<=cptcovage;kk++) {
                   4464:          if(!FixedV[Tvar[Tage[kk]]])
                   4465:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4466:          else
1.341     brouard  4467:            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.242     brouard  4468:        }
                   4469:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4470:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4471:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4472:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4473:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4474:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4475:        savm=oldm;
                   4476:        oldm=newm;
1.126     brouard  4477:       } /* end mult */
1.336     brouard  4478:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4479:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4480:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4481:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4482:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4483:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4484:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4485:         * probability in order to take into account the bias as a fraction of the way
                   4486:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4487:                                 * -stepm/2 to stepm/2 .
                   4488:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4489:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4490:                                 */
1.126     brouard  4491:       s1=s[mw[mi][i]][i];
                   4492:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4493:       /* if(s2==-1){ */
1.268     brouard  4494:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4495:       /*       /\* exit(1); *\/ */
                   4496:       /* } */
1.126     brouard  4497:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4498:       /* bias is positive if real duration
                   4499:        * is higher than the multiple of stepm and negative otherwise.
                   4500:        */
                   4501:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4502:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4503:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4504:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4505:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4506:        lli= log(survp);
1.126     brouard  4507:       }else if (mle==1){
1.242     brouard  4508:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4509:       } else if(mle==2){
1.242     brouard  4510:        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  4511:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4512:        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  4513:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4514:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4515:       } else{  /* mle=0 back to 1 */
1.242     brouard  4516:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4517:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4518:       } /* End of if */
                   4519:       ipmx +=1;
                   4520:       sw += weight[i];
                   4521:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4522:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4523:       /* 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  4524:       if(globpr){
1.246     brouard  4525:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4526:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4527:                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  4528:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4529:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4530:        /* %11.6f %11.6f %11.6f ", \ */
                   4531:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4532:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4533:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4534:          llt +=ll[k]*gipmx/gsw;
                   4535:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4536:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4537:        }
1.343     brouard  4538:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4539:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4540:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4541:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4542:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4543:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4544:        }
                   4545:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4546:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4547:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4548:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4549:            /* printf(" %g",cov[ioffset+ipos]); */
                   4550:          }else{
                   4551:            fprintf(ficresilk,"*");
                   4552:            /* printf("*"); */
1.342     brouard  4553:          }
1.343     brouard  4554:          iposold=ipos;
                   4555:        }
                   4556:        for (kk=1; kk<=cptcovage;kk++) {
                   4557:          if(!FixedV[Tvar[Tage[kk]]]){
                   4558:            fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]);
                   4559:            /* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4560:          }else{
                   4561:            fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4562:            /* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
1.342     brouard  4563:          }
1.343     brouard  4564:        }
                   4565:        /* printf("\n"); */
1.342     brouard  4566:        /* } /\*  End debugILK *\/ */
                   4567:        fprintf(ficresilk,"\n");
                   4568:       } /* End if globpr */
1.335     brouard  4569:     } /* end of wave */
                   4570:   } /* end of individual */
                   4571:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4572: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4573:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4574:   if(globpr==0){ /* First time we count the contributions and weights */
                   4575:     gipmx=ipmx;
                   4576:     gsw=sw;
                   4577:   }
1.343     brouard  4578:   return -l;
1.126     brouard  4579: }
                   4580: 
                   4581: 
                   4582: /*************** function likelione ***********/
1.292     brouard  4583: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4584: {
                   4585:   /* This routine should help understanding what is done with 
                   4586:      the selection of individuals/waves and
                   4587:      to check the exact contribution to the likelihood.
                   4588:      Plotting could be done.
1.342     brouard  4589:   */
                   4590:   void pstamp(FILE *ficres);
1.343     brouard  4591:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4592: 
                   4593:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4594:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4595:     strcat(fileresilk,fileresu);
1.126     brouard  4596:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4597:       printf("Problem with resultfile: %s\n", fileresilk);
                   4598:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4599:     }
1.342     brouard  4600:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4601:     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");
                   4602:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4603:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4604:     for(k=1; k<=nlstate; k++) 
                   4605:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4606:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4607: 
                   4608:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4609:       for(kf=1;kf <= ncovf; kf++){
                   4610:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4611:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4612:       }
                   4613:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4614:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4615:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4616:          /* printf(" %d",ipos); */
                   4617:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4618:        }else{
                   4619:          /* printf("*"); */
                   4620:          fprintf(ficresilk,"*");
1.343     brouard  4621:        }
1.342     brouard  4622:        iposold=ipos;
                   4623:       }
                   4624:       for (kk=1; kk<=cptcovage;kk++) {
                   4625:        if(!FixedV[Tvar[Tage[kk]]]){
                   4626:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4627:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4628:        }else{
                   4629:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4630:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4631:        }
                   4632:       }
                   4633:     /* } /\* End if debugILK *\/ */
                   4634:     /* printf("\n"); */
                   4635:     fprintf(ficresilk,"\n");
                   4636:   } /* End glogpri */
1.126     brouard  4637: 
1.292     brouard  4638:   *fretone=(*func)(p);
1.126     brouard  4639:   if(*globpri !=0){
                   4640:     fclose(ficresilk);
1.205     brouard  4641:     if (mle ==0)
                   4642:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4643:     else if(mle >=1)
                   4644:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4645:     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  4646:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4647:       
1.207     brouard  4648:     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  4649: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4650:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4651: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4652:     
                   4653:     for (k=1; k<= nlstate ; k++) {
                   4654:       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 \
                   4655: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4656:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   4657:        /* kvar=Tvar[TvarFind[kf]]; */ /* variable */
                   4658:        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): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   4659: <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]]);
                   4660:       }
                   4661:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4662:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4663:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4664:        /* 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]); */
                   4665:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4666:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4667:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4668:          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)  */
                   4669:            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> \
                   4670: <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);
                   4671:          } /* End only for dummies time varying (single?) */
                   4672:        }else{ /* Useless product */
                   4673:          /* printf("*"); */
                   4674:          /* fprintf(ficresilk,"*"); */ 
                   4675:        }
                   4676:        iposold=ipos;
                   4677:       } /* For each time varying covariate */
                   4678:     } /* End loop on states */
                   4679: 
                   4680: /*     if(debugILK){ */
                   4681: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4682: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4683: /*     for (k=1; k<= nlstate ; k++) { */
                   4684: /*       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> \ */
                   4685: /* <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]]); */
                   4686: /*     } */
                   4687: /*       } */
                   4688: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4689: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4690: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4691: /*     /\* 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]); *\/ */
                   4692: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4693: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4694: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4695: /*       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)  *\/ */
                   4696: /*         for (k=1; k<= nlstate ; k++) { */
                   4697: /*           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> \ */
                   4698: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4699: /*         } /\* End state *\/ */
                   4700: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4701: /*     }else{ /\* Useless product *\/ */
                   4702: /*       /\* printf("*"); *\/ */
                   4703: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4704: /*     } */
                   4705: /*     iposold=ipos; */
                   4706: /*       } /\* For each time varying covariate *\/ */
                   4707: /*     }/\* End debugILK *\/ */
1.207     brouard  4708:     fflush(fichtm);
1.343     brouard  4709:   }/* End globpri */
1.126     brouard  4710:   return;
                   4711: }
                   4712: 
                   4713: 
                   4714: /*********** Maximum Likelihood Estimation ***************/
                   4715: 
                   4716: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4717: {
1.319     brouard  4718:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4719:   double **xi;
                   4720:   double fret;
                   4721:   double fretone; /* Only one call to likelihood */
                   4722:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4723: 
                   4724: #ifdef NLOPT
                   4725:   int creturn;
                   4726:   nlopt_opt opt;
                   4727:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4728:   double *lb;
                   4729:   double minf; /* the minimum objective value, upon return */
                   4730:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4731:   myfunc_data dinst, *d = &dinst;
                   4732: #endif
                   4733: 
                   4734: 
1.126     brouard  4735:   xi=matrix(1,npar,1,npar);
                   4736:   for (i=1;i<=npar;i++)
                   4737:     for (j=1;j<=npar;j++)
                   4738:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4739:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4740:   strcpy(filerespow,"POW_"); 
1.126     brouard  4741:   strcat(filerespow,fileres);
                   4742:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4743:     printf("Problem with resultfile: %s\n", filerespow);
                   4744:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4745:   }
                   4746:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4747:   for (i=1;i<=nlstate;i++)
                   4748:     for(j=1;j<=nlstate+ndeath;j++)
                   4749:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4750:   fprintf(ficrespow,"\n");
1.162     brouard  4751: #ifdef POWELL
1.319     brouard  4752: #ifdef LINMINORIGINAL
                   4753: #else /* LINMINORIGINAL */
                   4754:   
                   4755:   flatdir=ivector(1,npar); 
                   4756:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4757: #endif /*LINMINORIGINAL */
                   4758: 
                   4759: #ifdef FLATSUP
                   4760:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4761:   /* reorganizing p by suppressing flat directions */
                   4762:   for(i=1, jk=1; i <=nlstate; i++){
                   4763:     for(k=1; k <=(nlstate+ndeath); k++){
                   4764:       if (k != i) {
                   4765:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4766:         if(flatdir[jk]==1){
                   4767:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4768:         }
                   4769:         for(j=1; j <=ncovmodel; j++){
                   4770:           printf("%12.7f ",p[jk]);
                   4771:           jk++; 
                   4772:         }
                   4773:         printf("\n");
                   4774:       }
                   4775:     }
                   4776:   }
                   4777: /* skipping */
                   4778:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4779:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4780:     for(k=1; k <=(nlstate+ndeath); k++){
                   4781:       if (k != i) {
                   4782:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4783:         if(flatdir[jk]==1){
                   4784:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4785:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4786:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4787:             /*q[jjk]=p[jk];*/
                   4788:           }
                   4789:         }else{
                   4790:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4791:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4792:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4793:             /*q[jjk]=p[jk];*/
                   4794:           }
                   4795:         }
                   4796:         printf("\n");
                   4797:       }
                   4798:       fflush(stdout);
                   4799:     }
                   4800:   }
                   4801:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4802: #else  /* FLATSUP */
1.126     brouard  4803:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4804: #endif  /* FLATSUP */
                   4805: 
                   4806: #ifdef LINMINORIGINAL
                   4807: #else
                   4808:       free_ivector(flatdir,1,npar); 
                   4809: #endif  /* LINMINORIGINAL*/
                   4810: #endif /* POWELL */
1.126     brouard  4811: 
1.162     brouard  4812: #ifdef NLOPT
                   4813: #ifdef NEWUOA
                   4814:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4815: #else
                   4816:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4817: #endif
                   4818:   lb=vector(0,npar-1);
                   4819:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4820:   nlopt_set_lower_bounds(opt, lb);
                   4821:   nlopt_set_initial_step1(opt, 0.1);
                   4822:   
                   4823:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4824:   d->function = func;
                   4825:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4826:   nlopt_set_min_objective(opt, myfunc, d);
                   4827:   nlopt_set_xtol_rel(opt, ftol);
                   4828:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4829:     printf("nlopt failed! %d\n",creturn); 
                   4830:   }
                   4831:   else {
                   4832:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4833:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4834:     iter=1; /* not equal */
                   4835:   }
                   4836:   nlopt_destroy(opt);
                   4837: #endif
1.319     brouard  4838: #ifdef FLATSUP
                   4839:   /* npared = npar -flatd/ncovmodel; */
                   4840:   /* xired= matrix(1,npared,1,npared); */
                   4841:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4842:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4843:   /* free_matrix(xire,1,npared,1,npared); */
                   4844: #else  /* FLATSUP */
                   4845: #endif /* FLATSUP */
1.126     brouard  4846:   free_matrix(xi,1,npar,1,npar);
                   4847:   fclose(ficrespow);
1.203     brouard  4848:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4849:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4850:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4851: 
                   4852: }
                   4853: 
                   4854: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4855: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4856: {
                   4857:   double  **a,**y,*x,pd;
1.203     brouard  4858:   /* double **hess; */
1.164     brouard  4859:   int i, j;
1.126     brouard  4860:   int *indx;
                   4861: 
                   4862:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4863:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4864:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4865:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4866:   double gompertz(double p[]);
1.203     brouard  4867:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4868: 
                   4869:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4870:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4871:   for (i=1;i<=npar;i++){
1.203     brouard  4872:     printf("%d-",i);fflush(stdout);
                   4873:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4874:    
                   4875:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4876:     
                   4877:     /*  printf(" %f ",p[i]);
                   4878:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4879:   }
                   4880:   
                   4881:   for (i=1;i<=npar;i++) {
                   4882:     for (j=1;j<=npar;j++)  {
                   4883:       if (j>i) { 
1.203     brouard  4884:        printf(".%d-%d",i,j);fflush(stdout);
                   4885:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4886:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4887:        
                   4888:        hess[j][i]=hess[i][j];    
                   4889:        /*printf(" %lf ",hess[i][j]);*/
                   4890:       }
                   4891:     }
                   4892:   }
                   4893:   printf("\n");
                   4894:   fprintf(ficlog,"\n");
                   4895: 
                   4896:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4897:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4898:   
                   4899:   a=matrix(1,npar,1,npar);
                   4900:   y=matrix(1,npar,1,npar);
                   4901:   x=vector(1,npar);
                   4902:   indx=ivector(1,npar);
                   4903:   for (i=1;i<=npar;i++)
                   4904:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4905:   ludcmp(a,npar,indx,&pd);
                   4906: 
                   4907:   for (j=1;j<=npar;j++) {
                   4908:     for (i=1;i<=npar;i++) x[i]=0;
                   4909:     x[j]=1;
                   4910:     lubksb(a,npar,indx,x);
                   4911:     for (i=1;i<=npar;i++){ 
                   4912:       matcov[i][j]=x[i];
                   4913:     }
                   4914:   }
                   4915: 
                   4916:   printf("\n#Hessian matrix#\n");
                   4917:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4918:   for (i=1;i<=npar;i++) { 
                   4919:     for (j=1;j<=npar;j++) { 
1.203     brouard  4920:       printf("%.6e ",hess[i][j]);
                   4921:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4922:     }
                   4923:     printf("\n");
                   4924:     fprintf(ficlog,"\n");
                   4925:   }
                   4926: 
1.203     brouard  4927:   /* printf("\n#Covariance matrix#\n"); */
                   4928:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4929:   /* for (i=1;i<=npar;i++) {  */
                   4930:   /*   for (j=1;j<=npar;j++) {  */
                   4931:   /*     printf("%.6e ",matcov[i][j]); */
                   4932:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4933:   /*   } */
                   4934:   /*   printf("\n"); */
                   4935:   /*   fprintf(ficlog,"\n"); */
                   4936:   /* } */
                   4937: 
1.126     brouard  4938:   /* Recompute Inverse */
1.203     brouard  4939:   /* for (i=1;i<=npar;i++) */
                   4940:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4941:   /* ludcmp(a,npar,indx,&pd); */
                   4942: 
                   4943:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4944: 
                   4945:   /* for (j=1;j<=npar;j++) { */
                   4946:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4947:   /*   x[j]=1; */
                   4948:   /*   lubksb(a,npar,indx,x); */
                   4949:   /*   for (i=1;i<=npar;i++){  */
                   4950:   /*     y[i][j]=x[i]; */
                   4951:   /*     printf("%.3e ",y[i][j]); */
                   4952:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4953:   /*   } */
                   4954:   /*   printf("\n"); */
                   4955:   /*   fprintf(ficlog,"\n"); */
                   4956:   /* } */
                   4957: 
                   4958:   /* Verifying the inverse matrix */
                   4959: #ifdef DEBUGHESS
                   4960:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4961: 
1.203     brouard  4962:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4963:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4964: 
                   4965:   for (j=1;j<=npar;j++) {
                   4966:     for (i=1;i<=npar;i++){ 
1.203     brouard  4967:       printf("%.2f ",y[i][j]);
                   4968:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4969:     }
                   4970:     printf("\n");
                   4971:     fprintf(ficlog,"\n");
                   4972:   }
1.203     brouard  4973: #endif
1.126     brouard  4974: 
                   4975:   free_matrix(a,1,npar,1,npar);
                   4976:   free_matrix(y,1,npar,1,npar);
                   4977:   free_vector(x,1,npar);
                   4978:   free_ivector(indx,1,npar);
1.203     brouard  4979:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4980: 
                   4981: 
                   4982: }
                   4983: 
                   4984: /*************** hessian matrix ****************/
                   4985: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4986: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4987:   int i;
                   4988:   int l=1, lmax=20;
1.203     brouard  4989:   double k1,k2, res, fx;
1.132     brouard  4990:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4991:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4992:   int k=0,kmax=10;
                   4993:   double l1;
                   4994: 
                   4995:   fx=func(x);
                   4996:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4997:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4998:     l1=pow(10,l);
                   4999:     delts=delt;
                   5000:     for(k=1 ; k <kmax; k=k+1){
                   5001:       delt = delta*(l1*k);
                   5002:       p2[theta]=x[theta] +delt;
1.145     brouard  5003:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5004:       p2[theta]=x[theta]-delt;
                   5005:       k2=func(p2)-fx;
                   5006:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5007:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5008:       
1.203     brouard  5009: #ifdef DEBUGHESSII
1.126     brouard  5010:       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);
                   5011:       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);
                   5012: #endif
                   5013:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5014:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5015:        k=kmax;
                   5016:       }
                   5017:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5018:        k=kmax; l=lmax*10;
1.126     brouard  5019:       }
                   5020:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5021:        delts=delt;
                   5022:       }
1.203     brouard  5023:     } /* End loop k */
1.126     brouard  5024:   }
                   5025:   delti[theta]=delts;
                   5026:   return res; 
                   5027:   
                   5028: }
                   5029: 
1.203     brouard  5030: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5031: {
                   5032:   int i;
1.164     brouard  5033:   int l=1, lmax=20;
1.126     brouard  5034:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5035:   double p2[MAXPARM+1];
1.203     brouard  5036:   int k, kmax=1;
                   5037:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5038: 
                   5039:   int firstime=0;
1.203     brouard  5040:   
1.126     brouard  5041:   fx=func(x);
1.203     brouard  5042:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5043:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5044:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5045:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5046:     k1=func(p2)-fx;
                   5047:   
1.203     brouard  5048:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5049:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5050:     k2=func(p2)-fx;
                   5051:   
1.203     brouard  5052:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5053:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5054:     k3=func(p2)-fx;
                   5055:   
1.203     brouard  5056:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5057:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5058:     k4=func(p2)-fx;
1.203     brouard  5059:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5060:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5061:       firstime=1;
1.203     brouard  5062:       kmax=kmax+10;
1.208     brouard  5063:     }
                   5064:     if(kmax >=10 || firstime ==1){
1.246     brouard  5065:       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);
                   5066:       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  5067:       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);
                   5068:       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);
                   5069:     }
                   5070: #ifdef DEBUGHESSIJ
                   5071:     v1=hess[thetai][thetai];
                   5072:     v2=hess[thetaj][thetaj];
                   5073:     cv12=res;
                   5074:     /* Computing eigen value of Hessian matrix */
                   5075:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5076:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5077:     if ((lc2 <0) || (lc1 <0) ){
                   5078:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5079:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5080:       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);
                   5081:       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);
                   5082:     }
1.126     brouard  5083: #endif
                   5084:   }
                   5085:   return res;
                   5086: }
                   5087: 
1.203     brouard  5088:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5089: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5090: /* { */
                   5091: /*   int i; */
                   5092: /*   int l=1, lmax=20; */
                   5093: /*   double k1,k2,k3,k4,res,fx; */
                   5094: /*   double p2[MAXPARM+1]; */
                   5095: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5096: /*   int k=0,kmax=10; */
                   5097: /*   double l1; */
                   5098:   
                   5099: /*   fx=func(x); */
                   5100: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5101: /*     l1=pow(10,l); */
                   5102: /*     delts=delt; */
                   5103: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5104: /*       delt = delti*(l1*k); */
                   5105: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5106: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5107: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5108: /*       k1=func(p2)-fx; */
                   5109:       
                   5110: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5111: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5112: /*       k2=func(p2)-fx; */
                   5113:       
                   5114: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5115: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5116: /*       k3=func(p2)-fx; */
                   5117:       
                   5118: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5119: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5120: /*       k4=func(p2)-fx; */
                   5121: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5122: /* #ifdef DEBUGHESSIJ */
                   5123: /*       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); */
                   5124: /*       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); */
                   5125: /* #endif */
                   5126: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5127: /*     k=kmax; */
                   5128: /*       } */
                   5129: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5130: /*     k=kmax; l=lmax*10; */
                   5131: /*       } */
                   5132: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5133: /*     delts=delt; */
                   5134: /*       } */
                   5135: /*     } /\* End loop k *\/ */
                   5136: /*   } */
                   5137: /*   delti[theta]=delts; */
                   5138: /*   return res;  */
                   5139: /* } */
                   5140: 
                   5141: 
1.126     brouard  5142: /************** Inverse of matrix **************/
                   5143: void ludcmp(double **a, int n, int *indx, double *d) 
                   5144: { 
                   5145:   int i,imax,j,k; 
                   5146:   double big,dum,sum,temp; 
                   5147:   double *vv; 
                   5148:  
                   5149:   vv=vector(1,n); 
                   5150:   *d=1.0; 
                   5151:   for (i=1;i<=n;i++) { 
                   5152:     big=0.0; 
                   5153:     for (j=1;j<=n;j++) 
                   5154:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5155:     if (big == 0.0){
                   5156:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5157:       for (j=1;j<=n;j++) {
                   5158:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5159:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5160:       }
                   5161:       fflush(ficlog);
                   5162:       fclose(ficlog);
                   5163:       nrerror("Singular matrix in routine ludcmp"); 
                   5164:     }
1.126     brouard  5165:     vv[i]=1.0/big; 
                   5166:   } 
                   5167:   for (j=1;j<=n;j++) { 
                   5168:     for (i=1;i<j;i++) { 
                   5169:       sum=a[i][j]; 
                   5170:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5171:       a[i][j]=sum; 
                   5172:     } 
                   5173:     big=0.0; 
                   5174:     for (i=j;i<=n;i++) { 
                   5175:       sum=a[i][j]; 
                   5176:       for (k=1;k<j;k++) 
                   5177:        sum -= a[i][k]*a[k][j]; 
                   5178:       a[i][j]=sum; 
                   5179:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5180:        big=dum; 
                   5181:        imax=i; 
                   5182:       } 
                   5183:     } 
                   5184:     if (j != imax) { 
                   5185:       for (k=1;k<=n;k++) { 
                   5186:        dum=a[imax][k]; 
                   5187:        a[imax][k]=a[j][k]; 
                   5188:        a[j][k]=dum; 
                   5189:       } 
                   5190:       *d = -(*d); 
                   5191:       vv[imax]=vv[j]; 
                   5192:     } 
                   5193:     indx[j]=imax; 
                   5194:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5195:     if (j != n) { 
                   5196:       dum=1.0/(a[j][j]); 
                   5197:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5198:     } 
                   5199:   } 
                   5200:   free_vector(vv,1,n);  /* Doesn't work */
                   5201: ;
                   5202: } 
                   5203: 
                   5204: void lubksb(double **a, int n, int *indx, double b[]) 
                   5205: { 
                   5206:   int i,ii=0,ip,j; 
                   5207:   double sum; 
                   5208:  
                   5209:   for (i=1;i<=n;i++) { 
                   5210:     ip=indx[i]; 
                   5211:     sum=b[ip]; 
                   5212:     b[ip]=b[i]; 
                   5213:     if (ii) 
                   5214:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5215:     else if (sum) ii=i; 
                   5216:     b[i]=sum; 
                   5217:   } 
                   5218:   for (i=n;i>=1;i--) { 
                   5219:     sum=b[i]; 
                   5220:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5221:     b[i]=sum/a[i][i]; 
                   5222:   } 
                   5223: } 
                   5224: 
                   5225: void pstamp(FILE *fichier)
                   5226: {
1.196     brouard  5227:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5228: }
                   5229: 
1.297     brouard  5230: void date2dmy(double date,double *day, double *month, double *year){
                   5231:   double yp=0., yp1=0., yp2=0.;
                   5232:   
                   5233:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5234:                        fractional in yp1 */
                   5235:   *year=yp;
                   5236:   yp2=modf((yp1*12),&yp);
                   5237:   *month=yp;
                   5238:   yp1=modf((yp2*30.5),&yp);
                   5239:   *day=yp;
                   5240:   if(*day==0) *day=1;
                   5241:   if(*month==0) *month=1;
                   5242: }
                   5243: 
1.253     brouard  5244: 
                   5245: 
1.126     brouard  5246: /************ Frequencies ********************/
1.251     brouard  5247: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5248:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5249:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5250: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5251:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5252:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5253:   int iind=0, iage=0;
                   5254:   int mi; /* Effective wave */
                   5255:   int first;
                   5256:   double ***freq; /* Frequencies */
1.268     brouard  5257:   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 */
                   5258:   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  5259:   double *meanq, *stdq, *idq;
1.226     brouard  5260:   double **meanqt;
                   5261:   double *pp, **prop, *posprop, *pospropt;
                   5262:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5263:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5264:   double agebegin, ageend;
                   5265:     
                   5266:   pp=vector(1,nlstate);
1.251     brouard  5267:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5268:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5269:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5270:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5271:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5272:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5273:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5274:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5275:   strcpy(fileresp,"P_");
                   5276:   strcat(fileresp,fileresu);
                   5277:   /*strcat(fileresphtm,fileresu);*/
                   5278:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5279:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5280:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5281:     exit(0);
                   5282:   }
1.240     brouard  5283:   
1.226     brouard  5284:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5285:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5286:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5287:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5288:     fflush(ficlog);
                   5289:     exit(70); 
                   5290:   }
                   5291:   else{
                   5292:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5293: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5294: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5295:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5296:   }
1.319     brouard  5297:   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  5298:   
1.226     brouard  5299:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5300:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5301:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5302:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5303:     fflush(ficlog);
                   5304:     exit(70); 
1.240     brouard  5305:   } else{
1.226     brouard  5306:     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  5307: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5308: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5309:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5310:   }
1.319     brouard  5311:   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  5312:   
1.253     brouard  5313:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5314:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5315:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5316:   j1=0;
1.126     brouard  5317:   
1.227     brouard  5318:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5319:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5320:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5321:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5322:   
                   5323:   
1.226     brouard  5324:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5325:      reference=low_education V1=0,V2=0
                   5326:      med_educ                V1=1 V2=0, 
                   5327:      high_educ               V1=0 V2=1
1.330     brouard  5328:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5329:   */
1.249     brouard  5330:   dateintsum=0;
                   5331:   k2cpt=0;
                   5332: 
1.253     brouard  5333:   if(cptcoveff == 0 )
1.265     brouard  5334:     nl=1;  /* Constant and age model only */
1.253     brouard  5335:   else
                   5336:     nl=2;
1.265     brouard  5337: 
                   5338:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5339:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5340:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5341:    *     freq[s1][s2][iage] =0.
                   5342:    *     Loop on iind
                   5343:    *       ++freq[s1][s2][iage] weighted
                   5344:    *     end iind
                   5345:    *     if covariate and j!0
                   5346:    *       headers Variable on one line
                   5347:    *     endif cov j!=0
                   5348:    *     header of frequency table by age
                   5349:    *     Loop on age
                   5350:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5351:    *       pos+=freq[s1][s2][iage] weighted
                   5352:    *       Loop on s1 initial state
                   5353:    *         fprintf(ficresp
                   5354:    *       end s1
                   5355:    *     end age
                   5356:    *     if j!=0 computes starting values
                   5357:    *     end compute starting values
                   5358:    *   end j1
                   5359:    * end nl 
                   5360:    */
1.253     brouard  5361:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5362:     if(nj==1)
                   5363:       j=0;  /* First pass for the constant */
1.265     brouard  5364:     else{
1.335     brouard  5365:       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  5366:     }
1.251     brouard  5367:     first=1;
1.332     brouard  5368:     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  5369:       posproptt=0.;
1.330     brouard  5370:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5371:        scanf("%d", i);*/
                   5372:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5373:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5374:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5375:            freq[i][s2][m]=0;
1.251     brouard  5376:       
                   5377:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5378:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5379:          prop[i][m]=0;
                   5380:        posprop[i]=0;
                   5381:        pospropt[i]=0;
                   5382:       }
1.283     brouard  5383:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5384:         idq[z1]=0.;
                   5385:         meanq[z1]=0.;
                   5386:         stdq[z1]=0.;
1.283     brouard  5387:       }
                   5388:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5389:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5390:       /*         meanqt[m][z1]=0.; */
                   5391:       /*       } */
                   5392:       /* }       */
1.251     brouard  5393:       /* dateintsum=0; */
                   5394:       /* k2cpt=0; */
                   5395:       
1.265     brouard  5396:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5397:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5398:        bool=1;
                   5399:        if(j !=0){
                   5400:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5401:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5402:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5403:                /* if(Tvaraff[z1] ==-20){ */
                   5404:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5405:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5406:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5407:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5408:                /* 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); */
                   5409:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5410:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5411:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5412:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5413:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5414:                  /* 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", */
                   5415:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5416:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5417:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5418:                } /* Onlyf fixed */
                   5419:              } /* end z1 */
1.335     brouard  5420:            } /* cptcoveff > 0 */
1.251     brouard  5421:          } /* end any */
                   5422:        }/* end j==0 */
1.265     brouard  5423:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5424:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5425:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5426:            m=mw[mi][iind];
                   5427:            if(j!=0){
                   5428:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5429:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5430:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5431:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5432:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5433:                    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  5434:                                                                                      value is -1, we don't select. It differs from the 
                   5435:                                                                                      constant and age model which counts them. */
                   5436:                      bool=0; /* not selected */
                   5437:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5438:                    /* i1=Tvaraff[z1]; */
                   5439:                    /* i2=TnsdVar[i1]; */
                   5440:                    /* i3=nbcode[i1][i2]; */
                   5441:                    /* i4=covar[i1][iind]; */
                   5442:                    /* if(i4 != i3){ */
                   5443:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5444:                      bool=0;
                   5445:                    }
                   5446:                  }
                   5447:                }
                   5448:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5449:            } /* end j==0 */
                   5450:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5451:            if(bool==1){ /*Selected */
1.251     brouard  5452:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5453:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5454:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5455:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5456:              if(m >=firstpass && m <=lastpass){
                   5457:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5458:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5459:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5460:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5461:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5462:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5463:                if (m<lastpass) {
                   5464:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5465:                  /*   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]); */
                   5466:                  if(s[m][iind]==-1)
                   5467:                    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.));
                   5468:                  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  5469:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5470:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5471:                      idq[z1]=idq[z1]+weight[iind];
                   5472:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5473:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5474:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5475:                    }
1.284     brouard  5476:                  }
1.251     brouard  5477:                  /* if((int)agev[m][iind] == 55) */
                   5478:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5479:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5480:                  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  5481:                }
1.251     brouard  5482:              } /* end if between passes */  
                   5483:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5484:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5485:                k2cpt++;
                   5486:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5487:              }
1.251     brouard  5488:            }else{
                   5489:              bool=1;
                   5490:            }/* end bool 2 */
                   5491:          } /* end m */
1.284     brouard  5492:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5493:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5494:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5495:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5496:          /* } */
1.251     brouard  5497:        } /* end bool */
                   5498:       } /* end iind = 1 to imx */
1.319     brouard  5499:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5500:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5501:       
                   5502:       
                   5503:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5504:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5505:         pstamp(ficresp);
1.335     brouard  5506:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5507:         pstamp(ficresp);
1.251     brouard  5508:        printf( "\n#********** Variable "); 
                   5509:        fprintf(ficresp, "\n#********** Variable "); 
                   5510:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5511:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5512:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5513:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5514:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5515:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5516:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5517:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5518:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5519:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5520:          }else{
1.330     brouard  5521:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5522:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5523:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5524:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5525:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5526:          }
                   5527:        }
                   5528:        printf( "**********\n#");
                   5529:        fprintf(ficresp, "**********\n#");
                   5530:        fprintf(ficresphtm, "**********</h3>\n");
                   5531:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5532:        fprintf(ficlog, "**********\n");
                   5533:       }
1.284     brouard  5534:       /*
                   5535:        Printing means of quantitative variables if any
                   5536:       */
                   5537:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5538:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5539:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5540:        if(weightopt==1){
                   5541:          printf(" Weighted mean and standard deviation of");
                   5542:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5543:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5544:        }
1.311     brouard  5545:        /* mu = \frac{w x}{\sum w}
                   5546:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5547:        */
                   5548:        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]));
                   5549:        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]));
                   5550:        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  5551:       }
                   5552:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5553:       /*       for(m=1;m<=lastpass;m++){ */
                   5554:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5555:       /*   } */
                   5556:       /* } */
1.283     brouard  5557: 
1.251     brouard  5558:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5559:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5560:         fprintf(ficresp, " Age");
1.335     brouard  5561:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5562:          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]]);
                   5563:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5564:        }
1.251     brouard  5565:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5566:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5567:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5568:       }
1.335     brouard  5569:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5570:       fprintf(ficresphtm, "\n");
                   5571:       
                   5572:       /* Header of frequency table by age */
                   5573:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5574:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5575:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5576:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5577:          if(s2!=0 && m!=0)
                   5578:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5579:        }
1.226     brouard  5580:       }
1.251     brouard  5581:       fprintf(ficresphtmfr, "\n");
                   5582:     
                   5583:       /* For each age */
                   5584:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5585:        fprintf(ficresphtm,"<tr>");
                   5586:        if(iage==iagemax+1){
                   5587:          fprintf(ficlog,"1");
                   5588:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5589:        }else if(iage==iagemax+2){
                   5590:          fprintf(ficlog,"0");
                   5591:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5592:        }else if(iage==iagemax+3){
                   5593:          fprintf(ficlog,"Total");
                   5594:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5595:        }else{
1.240     brouard  5596:          if(first==1){
1.251     brouard  5597:            first=0;
                   5598:            printf("See log file for details...\n");
                   5599:          }
                   5600:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5601:          fprintf(ficlog,"Age %d", iage);
                   5602:        }
1.265     brouard  5603:        for(s1=1; s1 <=nlstate ; s1++){
                   5604:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5605:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5606:        }
1.265     brouard  5607:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5608:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5609:            pos += freq[s1][m][iage];
                   5610:          if(pp[s1]>=1.e-10){
1.251     brouard  5611:            if(first==1){
1.265     brouard  5612:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5613:            }
1.265     brouard  5614:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5615:          }else{
                   5616:            if(first==1)
1.265     brouard  5617:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5618:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5619:          }
                   5620:        }
                   5621:       
1.265     brouard  5622:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5623:          /* posprop[s1]=0; */
                   5624:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5625:            pp[s1] += freq[s1][m][iage];
                   5626:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5627:       
                   5628:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5629:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5630:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5631:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5632:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5633:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5634:        }
                   5635:        
                   5636:        /* Writing ficresp */
1.335     brouard  5637:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5638:           if( iage <= iagemax){
                   5639:            fprintf(ficresp," %d",iage);
                   5640:           }
                   5641:         }else if( nj==2){
                   5642:           if( iage <= iagemax){
                   5643:            fprintf(ficresp," %d",iage);
1.335     brouard  5644:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5645:           }
1.240     brouard  5646:        }
1.265     brouard  5647:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5648:          if(pos>=1.e-5){
1.251     brouard  5649:            if(first==1)
1.265     brouard  5650:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5651:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5652:          }else{
                   5653:            if(first==1)
1.265     brouard  5654:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5655:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5656:          }
                   5657:          if( iage <= iagemax){
                   5658:            if(pos>=1.e-5){
1.335     brouard  5659:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5660:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5661:               }else if( nj==2){
                   5662:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5663:               }
                   5664:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5665:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5666:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5667:            } else{
1.335     brouard  5668:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5669:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5670:            }
1.240     brouard  5671:          }
1.265     brouard  5672:          pospropt[s1] +=posprop[s1];
                   5673:        } /* end loop s1 */
1.251     brouard  5674:        /* pospropt=0.; */
1.265     brouard  5675:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5676:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5677:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5678:              if(first==1){
1.265     brouard  5679:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5680:              }
1.265     brouard  5681:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5682:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5683:            }
1.265     brouard  5684:            if(s1!=0 && m!=0)
                   5685:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5686:          }
1.265     brouard  5687:        } /* end loop s1 */
1.251     brouard  5688:        posproptt=0.; 
1.265     brouard  5689:        for(s1=1; s1 <=nlstate; s1++){
                   5690:          posproptt += pospropt[s1];
1.251     brouard  5691:        }
                   5692:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5693:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5694:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5695:          if(iage <= iagemax)
                   5696:            fprintf(ficresp,"\n");
1.240     brouard  5697:        }
1.251     brouard  5698:        if(first==1)
                   5699:          printf("Others in log...\n");
                   5700:        fprintf(ficlog,"\n");
                   5701:       } /* end loop age iage */
1.265     brouard  5702:       
1.251     brouard  5703:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5704:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5705:        if(posproptt < 1.e-5){
1.265     brouard  5706:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5707:        }else{
1.265     brouard  5708:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5709:        }
1.226     brouard  5710:       }
1.251     brouard  5711:       fprintf(ficresphtm,"</tr>\n");
                   5712:       fprintf(ficresphtm,"</table>\n");
                   5713:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5714:       if(posproptt < 1.e-5){
1.251     brouard  5715:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5716:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5717:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5718:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5719:        invalidvarcomb[j1]=1;
1.226     brouard  5720:       }else{
1.338     brouard  5721:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5722:        invalidvarcomb[j1]=0;
1.226     brouard  5723:       }
1.251     brouard  5724:       fprintf(ficresphtmfr,"</table>\n");
                   5725:       fprintf(ficlog,"\n");
                   5726:       if(j!=0){
                   5727:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5728:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5729:          for(k=1; k <=(nlstate+ndeath); k++){
                   5730:            if (k != i) {
1.265     brouard  5731:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5732:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5733:                  if(j1==1){ /* All dummy covariates to zero */
                   5734:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5735:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5736:                    printf("%d%d ",i,k);
                   5737:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5738:                    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]));
                   5739:                    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]));
                   5740:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5741:                  }
1.253     brouard  5742:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5743:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5744:                    x[iage]= (double)iage;
                   5745:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5746:                    /* 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  5747:                  }
1.268     brouard  5748:                  /* Some are not finite, but linreg will ignore these ages */
                   5749:                  no=0;
1.253     brouard  5750:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5751:                  pstart[s1]=b;
                   5752:                  pstart[s1-1]=a;
1.252     brouard  5753:                }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 */ 
                   5754:                  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]);
                   5755:                  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  5756:                  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  5757:                  printf("%d%d ",i,k);
                   5758:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5759:                  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  5760:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5761:                  ;
                   5762:                }
                   5763:                /* printf("%12.7f )", param[i][jj][k]); */
                   5764:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5765:                s1++; 
1.251     brouard  5766:              } /* end jj */
                   5767:            } /* end k!= i */
                   5768:          } /* end k */
1.265     brouard  5769:        } /* end i, s1 */
1.251     brouard  5770:       } /* end j !=0 */
                   5771:     } /* end selected combination of covariate j1 */
                   5772:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5773:       printf("#Freqsummary: Starting values for the constants:\n");
                   5774:       fprintf(ficlog,"\n");
1.265     brouard  5775:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5776:        for(k=1; k <=(nlstate+ndeath); k++){
                   5777:          if (k != i) {
                   5778:            printf("%d%d ",i,k);
                   5779:            fprintf(ficlog,"%d%d ",i,k);
                   5780:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5781:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5782:              if(jj==1){ /* Age has to be done */
1.265     brouard  5783:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5784:                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]));
                   5785:                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  5786:              }
                   5787:              /* printf("%12.7f )", param[i][jj][k]); */
                   5788:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5789:              s1++; 
1.250     brouard  5790:            }
1.251     brouard  5791:            printf("\n");
                   5792:            fprintf(ficlog,"\n");
1.250     brouard  5793:          }
                   5794:        }
1.284     brouard  5795:       } /* end of state i */
1.251     brouard  5796:       printf("#Freqsummary\n");
                   5797:       fprintf(ficlog,"\n");
1.265     brouard  5798:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5799:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5800:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5801:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5802:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5803:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5804:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5805:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5806:          /* } */
                   5807:        }
1.265     brouard  5808:       } /* end loop s1 */
1.251     brouard  5809:       
                   5810:       printf("\n");
                   5811:       fprintf(ficlog,"\n");
                   5812:     } /* end j=0 */
1.249     brouard  5813:   } /* end j */
1.252     brouard  5814: 
1.253     brouard  5815:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5816:     for(i=1, jk=1; i <=nlstate; i++){
                   5817:       for(j=1; j <=nlstate+ndeath; j++){
                   5818:        if(j!=i){
                   5819:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5820:          printf("%1d%1d",i,j);
                   5821:          fprintf(ficparo,"%1d%1d",i,j);
                   5822:          for(k=1; k<=ncovmodel;k++){
                   5823:            /*    printf(" %lf",param[i][j][k]); */
                   5824:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5825:            p[jk]=pstart[jk];
                   5826:            printf(" %f ",pstart[jk]);
                   5827:            fprintf(ficparo," %f ",pstart[jk]);
                   5828:            jk++;
                   5829:          }
                   5830:          printf("\n");
                   5831:          fprintf(ficparo,"\n");
                   5832:        }
                   5833:       }
                   5834:     }
                   5835:   } /* end mle=-2 */
1.226     brouard  5836:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5837:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5838:   
1.226     brouard  5839:   fclose(ficresp);
                   5840:   fclose(ficresphtm);
                   5841:   fclose(ficresphtmfr);
1.283     brouard  5842:   free_vector(idq,1,nqfveff);
1.226     brouard  5843:   free_vector(meanq,1,nqfveff);
1.284     brouard  5844:   free_vector(stdq,1,nqfveff);
1.226     brouard  5845:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5846:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5847:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5848:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5849:   free_vector(pospropt,1,nlstate);
                   5850:   free_vector(posprop,1,nlstate);
1.251     brouard  5851:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5852:   free_vector(pp,1,nlstate);
                   5853:   /* End of freqsummary */
                   5854: }
1.126     brouard  5855: 
1.268     brouard  5856: /* Simple linear regression */
                   5857: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5858: 
                   5859:   /* y=a+bx regression */
                   5860:   double   sumx = 0.0;                        /* sum of x                      */
                   5861:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5862:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5863:   double   sumy = 0.0;                        /* sum of y                      */
                   5864:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5865:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5866:   double yhat;
                   5867:   
                   5868:   double denom=0;
                   5869:   int i;
                   5870:   int ne=*no;
                   5871:   
                   5872:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5873:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5874:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5875:       continue;
                   5876:     }
                   5877:     ne=ne+1;
                   5878:     sumx  += x[i];       
                   5879:     sumx2 += x[i]*x[i];  
                   5880:     sumxy += x[i] * y[i];
                   5881:     sumy  += y[i];      
                   5882:     sumy2 += y[i]*y[i]; 
                   5883:     denom = (ne * sumx2 - sumx*sumx);
                   5884:     /* 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); */
                   5885:   } 
                   5886:   
                   5887:   denom = (ne * sumx2 - sumx*sumx);
                   5888:   if (denom == 0) {
                   5889:     // vertical, slope m is infinity
                   5890:     *b = INFINITY;
                   5891:     *a = 0;
                   5892:     if (r) *r = 0;
                   5893:     return 1;
                   5894:   }
                   5895:   
                   5896:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5897:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5898:   if (r!=NULL) {
                   5899:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5900:       sqrt((sumx2 - sumx*sumx/ne) *
                   5901:           (sumy2 - sumy*sumy/ne));
                   5902:   }
                   5903:   *no=ne;
                   5904:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5905:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5906:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5907:       continue;
                   5908:     }
                   5909:     ne=ne+1;
                   5910:     yhat = y[i] - *a -*b* x[i];
                   5911:     sume2  += yhat * yhat ;       
                   5912:     
                   5913:     denom = (ne * sumx2 - sumx*sumx);
                   5914:     /* 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); */
                   5915:   } 
                   5916:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5917:   *sa= *sb * sqrt(sumx2/ne);
                   5918:   
                   5919:   return 0; 
                   5920: }
                   5921: 
1.126     brouard  5922: /************ Prevalence ********************/
1.227     brouard  5923: 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)
                   5924: {  
                   5925:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5926:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5927:      We still use firstpass and lastpass as another selection.
                   5928:   */
1.126     brouard  5929:  
1.227     brouard  5930:   int i, m, jk, j1, bool, z1,j, iv;
                   5931:   int mi; /* Effective wave */
                   5932:   int iage;
                   5933:   double agebegin, ageend;
                   5934: 
                   5935:   double **prop;
                   5936:   double posprop; 
                   5937:   double  y2; /* in fractional years */
                   5938:   int iagemin, iagemax;
                   5939:   int first; /** to stop verbosity which is redirected to log file */
                   5940: 
                   5941:   iagemin= (int) agemin;
                   5942:   iagemax= (int) agemax;
                   5943:   /*pp=vector(1,nlstate);*/
1.251     brouard  5944:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5945:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5946:   j1=0;
1.222     brouard  5947:   
1.227     brouard  5948:   /*j=cptcoveff;*/
                   5949:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5950:   
1.288     brouard  5951:   first=0;
1.335     brouard  5952:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5953:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5954:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5955:        prop[i][iage]=0.0;
                   5956:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5957:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5958:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5959:     
                   5960:     for (i=1; i<=imx; i++) { /* Each individual */
                   5961:       bool=1;
                   5962:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5963:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5964:        m=mw[mi][i];
                   5965:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5966:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5967:        for (z1=1; z1<=cptcoveff; z1++){
                   5968:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5969:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5970:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5971:              bool=0;
                   5972:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5973:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5974:              bool=0;
                   5975:            }
                   5976:        }
                   5977:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5978:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5979:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5980:          if(m >=firstpass && m <=lastpass){
                   5981:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5982:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5983:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5984:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5985:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5986:                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); 
                   5987:                exit(1);
                   5988:              }
                   5989:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5990:                /*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]]);*/
                   5991:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5992:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5993:              } /* end valid statuses */ 
                   5994:            } /* end selection of dates */
                   5995:          } /* end selection of waves */
                   5996:        } /* end bool */
                   5997:       } /* end wave */
                   5998:     } /* end individual */
                   5999:     for(i=iagemin; i <= iagemax+3; i++){  
                   6000:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6001:        posprop += prop[jk][i]; 
                   6002:       } 
                   6003:       
                   6004:       for(jk=1; jk <=nlstate ; jk++){      
                   6005:        if( i <=  iagemax){ 
                   6006:          if(posprop>=1.e-5){ 
                   6007:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6008:          } else{
1.288     brouard  6009:            if(!first){
                   6010:              first=1;
1.266     brouard  6011:              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]);
                   6012:            }else{
1.288     brouard  6013:              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  6014:            }
                   6015:          }
                   6016:        } 
                   6017:       }/* end jk */ 
                   6018:     }/* end i */ 
1.222     brouard  6019:      /*} *//* end i1 */
1.227     brouard  6020:   } /* end j1 */
1.222     brouard  6021:   
1.227     brouard  6022:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6023:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6024:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6025: }  /* End of prevalence */
1.126     brouard  6026: 
                   6027: /************* Waves Concatenation ***************/
                   6028: 
                   6029: 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)
                   6030: {
1.298     brouard  6031:   /* 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  6032:      Death is a valid wave (if date is known).
                   6033:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6034:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6035:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6036:   */
1.126     brouard  6037: 
1.224     brouard  6038:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6039:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6040:      double sum=0., jmean=0.;*/
1.224     brouard  6041:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6042:   int j, k=0,jk, ju, jl;
                   6043:   double sum=0.;
                   6044:   first=0;
1.214     brouard  6045:   firstwo=0;
1.217     brouard  6046:   firsthree=0;
1.218     brouard  6047:   firstfour=0;
1.164     brouard  6048:   jmin=100000;
1.126     brouard  6049:   jmax=-1;
                   6050:   jmean=0.;
1.224     brouard  6051: 
                   6052: /* Treating live states */
1.214     brouard  6053:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6054:     mi=0;  /* First valid wave */
1.227     brouard  6055:     mli=0; /* Last valid wave */
1.309     brouard  6056:     m=firstpass;  /* Loop on waves */
                   6057:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6058:       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 */
                   6059:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6060:       }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  6061:        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  6062:        mli=m;
1.224     brouard  6063:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6064:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6065:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6066:       }
1.309     brouard  6067:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6068: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6069:        break;
1.224     brouard  6070: #else
1.317     brouard  6071:        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  6072:          if(firsthree == 0){
1.302     brouard  6073:            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  6074:            firsthree=1;
1.317     brouard  6075:          }else if(firsthree >=1 && firsthree < 10){
                   6076:            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);
                   6077:            firsthree++;
                   6078:          }else if(firsthree == 10){
                   6079:            printf("Information, too many Information flags: no more reported to log either\n");
                   6080:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6081:            firsthree++;
                   6082:          }else{
                   6083:            firsthree++;
1.227     brouard  6084:          }
1.309     brouard  6085:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6086:          mli=m;
                   6087:        }
                   6088:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6089:          nbwarn++;
1.309     brouard  6090:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6091:            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);
                   6092:            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);
                   6093:          }
                   6094:          break;
                   6095:        }
                   6096:        break;
1.224     brouard  6097: #endif
1.227     brouard  6098:       }/* End m >= lastpass */
1.126     brouard  6099:     }/* end while */
1.224     brouard  6100: 
1.227     brouard  6101:     /* 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  6102:     /* After last pass */
1.224     brouard  6103: /* Treating death states */
1.214     brouard  6104:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6105:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6106:       /* } */
1.126     brouard  6107:       mi++;    /* Death is another wave */
                   6108:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6109:       /* Only death is a correct wave */
1.126     brouard  6110:       mw[mi][i]=m;
1.257     brouard  6111:     } /* else not in a death state */
1.224     brouard  6112: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6113:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6114:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6115:        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  6116:          nbwarn++;
                   6117:          if(firstfiv==0){
1.309     brouard  6118:            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  6119:            firstfiv=1;
                   6120:          }else{
1.309     brouard  6121:            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  6122:          }
1.309     brouard  6123:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6124:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6125:          nberr++;
                   6126:          if(firstwo==0){
1.309     brouard  6127:            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  6128:            firstwo=1;
                   6129:          }
1.309     brouard  6130:          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  6131:        }
1.257     brouard  6132:       }else{ /* if date of interview is unknown */
1.227     brouard  6133:        /* death is known but not confirmed by death status at any wave */
                   6134:        if(firstfour==0){
1.309     brouard  6135:          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  6136:          firstfour=1;
                   6137:        }
1.309     brouard  6138:        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  6139:       }
1.224     brouard  6140:     } /* end if date of death is known */
                   6141: #endif
1.309     brouard  6142:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6143:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6144:     if(mi==0){
                   6145:       nbwarn++;
                   6146:       if(first==0){
1.227     brouard  6147:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6148:        first=1;
1.126     brouard  6149:       }
                   6150:       if(first==1){
1.227     brouard  6151:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6152:       }
                   6153:     } /* end mi==0 */
                   6154:   } /* End individuals */
1.214     brouard  6155:   /* wav and mw are no more changed */
1.223     brouard  6156:        
1.317     brouard  6157:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6158:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6159: 
                   6160: 
1.126     brouard  6161:   for(i=1; i<=imx; i++){
                   6162:     for(mi=1; mi<wav[i];mi++){
                   6163:       if (stepm <=0)
1.227     brouard  6164:        dh[mi][i]=1;
1.126     brouard  6165:       else{
1.260     brouard  6166:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6167:          if (agedc[i] < 2*AGESUP) {
                   6168:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6169:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6170:            else if(j<0){
                   6171:              nberr++;
                   6172:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6173:              j=1; /* Temporary Dangerous patch */
                   6174:              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);
                   6175:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6176:              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);
                   6177:            }
                   6178:            k=k+1;
                   6179:            if (j >= jmax){
                   6180:              jmax=j;
                   6181:              ijmax=i;
                   6182:            }
                   6183:            if (j <= jmin){
                   6184:              jmin=j;
                   6185:              ijmin=i;
                   6186:            }
                   6187:            sum=sum+j;
                   6188:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6189:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6190:          }
                   6191:        }
                   6192:        else{
                   6193:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6194: /*       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  6195:                                        
1.227     brouard  6196:          k=k+1;
                   6197:          if (j >= jmax) {
                   6198:            jmax=j;
                   6199:            ijmax=i;
                   6200:          }
                   6201:          else if (j <= jmin){
                   6202:            jmin=j;
                   6203:            ijmin=i;
                   6204:          }
                   6205:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6206:          /*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]);*/
                   6207:          if(j<0){
                   6208:            nberr++;
                   6209:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6210:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6211:          }
                   6212:          sum=sum+j;
                   6213:        }
                   6214:        jk= j/stepm;
                   6215:        jl= j -jk*stepm;
                   6216:        ju= j -(jk+1)*stepm;
                   6217:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6218:          if(jl==0){
                   6219:            dh[mi][i]=jk;
                   6220:            bh[mi][i]=0;
                   6221:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6222:                  * to avoid the price of an extra matrix product in likelihood */
                   6223:            dh[mi][i]=jk+1;
                   6224:            bh[mi][i]=ju;
                   6225:          }
                   6226:        }else{
                   6227:          if(jl <= -ju){
                   6228:            dh[mi][i]=jk;
                   6229:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6230:                                 * is higher than the multiple of stepm and negative otherwise.
                   6231:                                 */
                   6232:          }
                   6233:          else{
                   6234:            dh[mi][i]=jk+1;
                   6235:            bh[mi][i]=ju;
                   6236:          }
                   6237:          if(dh[mi][i]==0){
                   6238:            dh[mi][i]=1; /* At least one step */
                   6239:            bh[mi][i]=ju; /* At least one step */
                   6240:            /*  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);*/
                   6241:          }
                   6242:        } /* end if mle */
1.126     brouard  6243:       }
                   6244:     } /* end wave */
                   6245:   }
                   6246:   jmean=sum/k;
                   6247:   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  6248:   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  6249: }
1.126     brouard  6250: 
                   6251: /*********** Tricode ****************************/
1.220     brouard  6252:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6253:  {
                   6254:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6255:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6256:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6257:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6258:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6259:     */
1.130     brouard  6260: 
1.242     brouard  6261:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6262:    int modmaxcovj=0; /* Modality max of covariates j */
                   6263:    int cptcode=0; /* Modality max of covariates j */
                   6264:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6265: 
                   6266: 
1.242     brouard  6267:    /* cptcoveff=0;  */
                   6268:    /* *cptcov=0; */
1.126     brouard  6269:  
1.242     brouard  6270:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6271:    for (k=1; k <= maxncov; k++)
                   6272:      for(j=1; j<=2; j++)
                   6273:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6274: 
1.242     brouard  6275:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6276:    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  6277:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6278:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.339     brouard  6279:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6280:        switch(Fixed[k]) {
                   6281:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6282:         modmaxcovj=0;
                   6283:         modmincovj=0;
1.242     brouard  6284:         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  6285:           /* 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  6286:           ij=(int)(covar[Tvar[k]][i]);
                   6287:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6288:            * If product of Vn*Vm, still boolean *:
                   6289:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6290:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6291:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6292:              modality of the nth covariate of individual i. */
                   6293:           if (ij > modmaxcovj)
                   6294:             modmaxcovj=ij; 
                   6295:           else if (ij < modmincovj) 
                   6296:             modmincovj=ij; 
1.287     brouard  6297:           if (ij <0 || ij >1 ){
1.311     brouard  6298:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6299:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6300:             fflush(ficlog);
                   6301:             exit(1);
1.287     brouard  6302:           }
                   6303:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6304:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6305:             exit(1);
                   6306:           }else
                   6307:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6308:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6309:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6310:           /* getting the maximum value of the modality of the covariate
                   6311:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6312:              female ies 1, then modmaxcovj=1.
                   6313:           */
                   6314:         } /* end for loop on individuals i */
                   6315:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6316:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6317:         cptcode=modmaxcovj;
                   6318:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6319:         /*for (i=0; i<=cptcode; i++) {*/
                   6320:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6321:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6322:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6323:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6324:             if( j != -1){
                   6325:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6326:                                  covariate for which somebody answered excluding 
                   6327:                                  undefined. Usually 2: 0 and 1. */
                   6328:             }
                   6329:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6330:                                     covariate for which somebody answered including 
                   6331:                                     undefined. Usually 3: -1, 0 and 1. */
                   6332:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6333:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6334:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6335:                        
1.242     brouard  6336:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6337:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6338:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6339:         /* modmincovj=3; modmaxcovj = 7; */
                   6340:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6341:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6342:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6343:         /* nbcode[Tvar[j]][ij]=k; */
                   6344:         /* nbcode[Tvar[j]][1]=0; */
                   6345:         /* nbcode[Tvar[j]][2]=1; */
                   6346:         /* nbcode[Tvar[j]][3]=2; */
                   6347:         /* To be continued (not working yet). */
                   6348:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6349: 
                   6350:         /* 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*/
                   6351:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6352:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6353:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6354:         /*, could be restored in the future */
                   6355:         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  6356:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6357:             break;
                   6358:           }
                   6359:           ij++;
1.287     brouard  6360:           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  6361:           cptcode = ij; /* New max modality for covar j */
                   6362:         } /* end of loop on modality i=-1 to 1 or more */
                   6363:         break;
                   6364:        case 1: /* Testing on varying covariate, could be simple and
                   6365:                * should look at waves or product of fixed *
                   6366:                * varying. No time to test -1, assuming 0 and 1 only */
                   6367:         ij=0;
                   6368:         for(i=0; i<=1;i++){
                   6369:           nbcode[Tvar[k]][++ij]=i;
                   6370:         }
                   6371:         break;
                   6372:        default:
                   6373:         break;
                   6374:        } /* end switch */
                   6375:      } /* end dummy test */
1.342     brouard  6376:      if(Dummy[k]==1 && Typevar[k] !=1 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6377:        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  6378:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6379:           printf("Error k=%d \n",k);
                   6380:           exit(1);
                   6381:         }
1.311     brouard  6382:         if(isnan(covar[Tvar[k]][i])){
                   6383:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6384:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6385:           fflush(ficlog);
                   6386:           exit(1);
                   6387:          }
                   6388:        }
1.335     brouard  6389:      } /* end Quanti */
1.287     brouard  6390:    } /* 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  6391:   
                   6392:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6393:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6394:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6395:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6396:      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 */ 
                   6397:      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 */
                   6398:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6399:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6400:   
                   6401:    ij=0;
                   6402:    /* 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  6403:    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 */
                   6404:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6405:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6406:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6407:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6408:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6409:        /* 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  6410:        /* If product not in single variable we don't print results */
                   6411:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6412:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6413:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6414:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6415:        /* ij            1    2                                            3  */  
                   6416:        /* Tvaraff[ij]=  4    3                                            1  */
                   6417:        /* Tmodelind[ij]=2    3                                            9  */
                   6418:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6419:        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*/
                   6420:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6421:        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 */
                   6422:        if(Fixed[k]!=0)
                   6423:         anyvaryingduminmodel=1;
                   6424:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6425:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6426:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6427:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6428:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6429:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6430:      } 
                   6431:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6432:    /* ij--; */
                   6433:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6434:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6435:                * because they can be excluded from the model and real
                   6436:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6437:    for(j=ij+1; j<= cptcovt; j++){
                   6438:      Tvaraff[j]=0;
                   6439:      Tmodelind[j]=0;
                   6440:    }
                   6441:    for(j=ntveff+1; j<= cptcovt; j++){
                   6442:      TmodelInvind[j]=0;
                   6443:    }
                   6444:    /* To be sorted */
                   6445:    ;
                   6446:  }
1.126     brouard  6447: 
1.145     brouard  6448: 
1.126     brouard  6449: /*********** Health Expectancies ****************/
                   6450: 
1.235     brouard  6451:  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  6452: 
                   6453: {
                   6454:   /* Health expectancies, no variances */
1.329     brouard  6455:   /* cij is the combination in the list of combination of dummy covariates */
                   6456:   /* strstart is a string of time at start of computing */
1.164     brouard  6457:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6458:   int nhstepma, nstepma; /* Decreasing with age */
                   6459:   double age, agelim, hf;
                   6460:   double ***p3mat;
                   6461:   double eip;
                   6462: 
1.238     brouard  6463:   /* pstamp(ficreseij); */
1.126     brouard  6464:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6465:   fprintf(ficreseij,"# Age");
                   6466:   for(i=1; i<=nlstate;i++){
                   6467:     for(j=1; j<=nlstate;j++){
                   6468:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6469:     }
                   6470:     fprintf(ficreseij," e%1d. ",i);
                   6471:   }
                   6472:   fprintf(ficreseij,"\n");
                   6473: 
                   6474:   
                   6475:   if(estepm < stepm){
                   6476:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6477:   }
                   6478:   else  hstepm=estepm;   
                   6479:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6480:    * This is mainly to measure the difference between two models: for example
                   6481:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6482:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6483:    * progression in between and thus overestimating or underestimating according
                   6484:    * to the curvature of the survival function. If, for the same date, we 
                   6485:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6486:    * to compare the new estimate of Life expectancy with the same linear 
                   6487:    * hypothesis. A more precise result, taking into account a more precise
                   6488:    * curvature will be obtained if estepm is as small as stepm. */
                   6489: 
                   6490:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6491:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6492:      nhstepm is the number of hstepm from age to agelim 
                   6493:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6494:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6495:      and note for a fixed period like estepm months */
                   6496:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6497:      survival function given by stepm (the optimization length). Unfortunately it
                   6498:      means that if the survival funtion is printed only each two years of age and if
                   6499:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6500:      results. So we changed our mind and took the option of the best precision.
                   6501:   */
                   6502:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6503: 
                   6504:   agelim=AGESUP;
                   6505:   /* If stepm=6 months */
                   6506:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6507:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6508:     
                   6509: /* nhstepm age range expressed in number of stepm */
                   6510:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6511:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6512:   /* if (stepm >= YEARM) hstepm=1;*/
                   6513:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6514:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6515: 
                   6516:   for (age=bage; age<=fage; age ++){ 
                   6517:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6518:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6519:     /* if (stepm >= YEARM) hstepm=1;*/
                   6520:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6521: 
                   6522:     /* If stepm=6 months */
                   6523:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6524:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6525:     /* 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  6526:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6527:     
                   6528:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6529:     
                   6530:     printf("%d|",(int)age);fflush(stdout);
                   6531:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6532:     
                   6533:     /* Computing expectancies */
                   6534:     for(i=1; i<=nlstate;i++)
                   6535:       for(j=1; j<=nlstate;j++)
                   6536:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6537:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6538:          
                   6539:          /* 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]);*/
                   6540: 
                   6541:        }
                   6542: 
                   6543:     fprintf(ficreseij,"%3.0f",age );
                   6544:     for(i=1; i<=nlstate;i++){
                   6545:       eip=0;
                   6546:       for(j=1; j<=nlstate;j++){
                   6547:        eip +=eij[i][j][(int)age];
                   6548:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6549:       }
                   6550:       fprintf(ficreseij,"%9.4f", eip );
                   6551:     }
                   6552:     fprintf(ficreseij,"\n");
                   6553:     
                   6554:   }
                   6555:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6556:   printf("\n");
                   6557:   fprintf(ficlog,"\n");
                   6558:   
                   6559: }
                   6560: 
1.235     brouard  6561:  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  6562: 
                   6563: {
                   6564:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6565:      to initial status i, ei. .
1.126     brouard  6566:   */
1.336     brouard  6567:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6568:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6569:   int nhstepma, nstepma; /* Decreasing with age */
                   6570:   double age, agelim, hf;
                   6571:   double ***p3matp, ***p3matm, ***varhe;
                   6572:   double **dnewm,**doldm;
                   6573:   double *xp, *xm;
                   6574:   double **gp, **gm;
                   6575:   double ***gradg, ***trgradg;
                   6576:   int theta;
                   6577: 
                   6578:   double eip, vip;
                   6579: 
                   6580:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6581:   xp=vector(1,npar);
                   6582:   xm=vector(1,npar);
                   6583:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6584:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6585:   
                   6586:   pstamp(ficresstdeij);
                   6587:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6588:   fprintf(ficresstdeij,"# Age");
                   6589:   for(i=1; i<=nlstate;i++){
                   6590:     for(j=1; j<=nlstate;j++)
                   6591:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6592:     fprintf(ficresstdeij," e%1d. ",i);
                   6593:   }
                   6594:   fprintf(ficresstdeij,"\n");
                   6595: 
                   6596:   pstamp(ficrescveij);
                   6597:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6598:   fprintf(ficrescveij,"# Age");
                   6599:   for(i=1; i<=nlstate;i++)
                   6600:     for(j=1; j<=nlstate;j++){
                   6601:       cptj= (j-1)*nlstate+i;
                   6602:       for(i2=1; i2<=nlstate;i2++)
                   6603:        for(j2=1; j2<=nlstate;j2++){
                   6604:          cptj2= (j2-1)*nlstate+i2;
                   6605:          if(cptj2 <= cptj)
                   6606:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6607:        }
                   6608:     }
                   6609:   fprintf(ficrescveij,"\n");
                   6610:   
                   6611:   if(estepm < stepm){
                   6612:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6613:   }
                   6614:   else  hstepm=estepm;   
                   6615:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6616:    * This is mainly to measure the difference between two models: for example
                   6617:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6618:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6619:    * progression in between and thus overestimating or underestimating according
                   6620:    * to the curvature of the survival function. If, for the same date, we 
                   6621:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6622:    * to compare the new estimate of Life expectancy with the same linear 
                   6623:    * hypothesis. A more precise result, taking into account a more precise
                   6624:    * curvature will be obtained if estepm is as small as stepm. */
                   6625: 
                   6626:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6627:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6628:      nhstepm is the number of hstepm from age to agelim 
                   6629:      nstepm is the number of stepm from age to agelin. 
                   6630:      Look at hpijx to understand the reason of that which relies in memory size
                   6631:      and note for a fixed period like estepm months */
                   6632:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6633:      survival function given by stepm (the optimization length). Unfortunately it
                   6634:      means that if the survival funtion is printed only each two years of age and if
                   6635:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6636:      results. So we changed our mind and took the option of the best precision.
                   6637:   */
                   6638:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6639: 
                   6640:   /* If stepm=6 months */
                   6641:   /* nhstepm age range expressed in number of stepm */
                   6642:   agelim=AGESUP;
                   6643:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6644:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6645:   /* if (stepm >= YEARM) hstepm=1;*/
                   6646:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6647:   
                   6648:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6649:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6650:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6651:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6652:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6653:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6654: 
                   6655:   for (age=bage; age<=fage; age ++){ 
                   6656:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6657:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6658:     /* if (stepm >= YEARM) hstepm=1;*/
                   6659:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6660:                
1.126     brouard  6661:     /* If stepm=6 months */
                   6662:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6663:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6664:     
                   6665:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6666:                
1.126     brouard  6667:     /* Computing  Variances of health expectancies */
                   6668:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6669:        decrease memory allocation */
                   6670:     for(theta=1; theta <=npar; theta++){
                   6671:       for(i=1; i<=npar; i++){ 
1.222     brouard  6672:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6673:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6674:       }
1.235     brouard  6675:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6676:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6677:                        
1.126     brouard  6678:       for(j=1; j<= nlstate; j++){
1.222     brouard  6679:        for(i=1; i<=nlstate; i++){
                   6680:          for(h=0; h<=nhstepm-1; h++){
                   6681:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6682:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6683:          }
                   6684:        }
1.126     brouard  6685:       }
1.218     brouard  6686:                        
1.126     brouard  6687:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6688:        for(h=0; h<=nhstepm-1; h++){
                   6689:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6690:        }
1.126     brouard  6691:     }/* End theta */
                   6692:     
                   6693:     
                   6694:     for(h=0; h<=nhstepm-1; h++)
                   6695:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6696:        for(theta=1; theta <=npar; theta++)
                   6697:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6698:     
1.218     brouard  6699:                
1.222     brouard  6700:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6701:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6702:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6703:                
1.222     brouard  6704:     printf("%d|",(int)age);fflush(stdout);
                   6705:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6706:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6707:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6708:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6709:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6710:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6711:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6712:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6713:       }
                   6714:     }
1.320     brouard  6715:     /* if((int)age ==50){ */
                   6716:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6717:     /* } */
1.126     brouard  6718:     /* Computing expectancies */
1.235     brouard  6719:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6720:     for(i=1; i<=nlstate;i++)
                   6721:       for(j=1; j<=nlstate;j++)
1.222     brouard  6722:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6723:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6724:                                        
1.222     brouard  6725:          /* 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  6726:                                        
1.222     brouard  6727:        }
1.269     brouard  6728: 
                   6729:     /* Standard deviation of expectancies ij */                
1.126     brouard  6730:     fprintf(ficresstdeij,"%3.0f",age );
                   6731:     for(i=1; i<=nlstate;i++){
                   6732:       eip=0.;
                   6733:       vip=0.;
                   6734:       for(j=1; j<=nlstate;j++){
1.222     brouard  6735:        eip += eij[i][j][(int)age];
                   6736:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6737:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6738:        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  6739:       }
                   6740:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6741:     }
                   6742:     fprintf(ficresstdeij,"\n");
1.218     brouard  6743:                
1.269     brouard  6744:     /* Variance of expectancies ij */          
1.126     brouard  6745:     fprintf(ficrescveij,"%3.0f",age );
                   6746:     for(i=1; i<=nlstate;i++)
                   6747:       for(j=1; j<=nlstate;j++){
1.222     brouard  6748:        cptj= (j-1)*nlstate+i;
                   6749:        for(i2=1; i2<=nlstate;i2++)
                   6750:          for(j2=1; j2<=nlstate;j2++){
                   6751:            cptj2= (j2-1)*nlstate+i2;
                   6752:            if(cptj2 <= cptj)
                   6753:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6754:          }
1.126     brouard  6755:       }
                   6756:     fprintf(ficrescveij,"\n");
1.218     brouard  6757:                
1.126     brouard  6758:   }
                   6759:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6760:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6761:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6762:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6763:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6764:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6765:   printf("\n");
                   6766:   fprintf(ficlog,"\n");
1.218     brouard  6767:        
1.126     brouard  6768:   free_vector(xm,1,npar);
                   6769:   free_vector(xp,1,npar);
                   6770:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6771:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6772:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6773: }
1.218     brouard  6774:  
1.126     brouard  6775: /************ Variance ******************/
1.235     brouard  6776:  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  6777:  {
1.279     brouard  6778:    /** Variance of health expectancies 
                   6779:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6780:     * double **newm;
                   6781:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6782:     */
1.218     brouard  6783:   
                   6784:    /* int movingaverage(); */
                   6785:    double **dnewm,**doldm;
                   6786:    double **dnewmp,**doldmp;
                   6787:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6788:    int first=0;
1.218     brouard  6789:    int k;
                   6790:    double *xp;
1.279     brouard  6791:    double **gp, **gm;  /**< for var eij */
                   6792:    double ***gradg, ***trgradg; /**< for var eij */
                   6793:    double **gradgp, **trgradgp; /**< for var p point j */
                   6794:    double *gpp, *gmp; /**< for var p point j */
                   6795:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6796:    double ***p3mat;
                   6797:    double age,agelim, hf;
                   6798:    /* double ***mobaverage; */
                   6799:    int theta;
                   6800:    char digit[4];
                   6801:    char digitp[25];
                   6802: 
                   6803:    char fileresprobmorprev[FILENAMELENGTH];
                   6804: 
                   6805:    if(popbased==1){
                   6806:      if(mobilav!=0)
                   6807:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6808:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6809:    }
                   6810:    else 
                   6811:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6812: 
1.218     brouard  6813:    /* if (mobilav!=0) { */
                   6814:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6815:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6816:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6817:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6818:    /*   } */
                   6819:    /* } */
                   6820: 
                   6821:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6822:    sprintf(digit,"%-d",ij);
                   6823:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6824:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6825:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6826:    strcat(fileresprobmorprev,fileresu);
                   6827:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6828:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6829:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6830:    }
                   6831:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6832:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6833:    pstamp(ficresprobmorprev);
                   6834:    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  6835:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6836: 
                   6837:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6838:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6839:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6840:    /* } */
                   6841:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  6842:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  6843:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6844:    }
1.337     brouard  6845:    /* for(j=1;j<=cptcoveff;j++)  */
                   6846:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6847:    fprintf(ficresprobmorprev,"\n");
                   6848: 
1.218     brouard  6849:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6850:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6851:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6852:      for(i=1; i<=nlstate;i++)
                   6853:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6854:    }  
                   6855:    fprintf(ficresprobmorprev,"\n");
                   6856:   
                   6857:    fprintf(ficgp,"\n# Routine varevsij");
                   6858:    fprintf(ficgp,"\nunset title \n");
                   6859:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6860:    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");
                   6861:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6862: 
1.218     brouard  6863:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6864:    pstamp(ficresvij);
                   6865:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6866:    if(popbased==1)
                   6867:      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);
                   6868:    else
                   6869:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6870:    fprintf(ficresvij,"# Age");
                   6871:    for(i=1; i<=nlstate;i++)
                   6872:      for(j=1; j<=nlstate;j++)
                   6873:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6874:    fprintf(ficresvij,"\n");
                   6875: 
                   6876:    xp=vector(1,npar);
                   6877:    dnewm=matrix(1,nlstate,1,npar);
                   6878:    doldm=matrix(1,nlstate,1,nlstate);
                   6879:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6880:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6881: 
                   6882:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6883:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6884:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6885:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6886:   
1.218     brouard  6887:    if(estepm < stepm){
                   6888:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6889:    }
                   6890:    else  hstepm=estepm;   
                   6891:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6892:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6893:       nhstepm is the number of hstepm from age to agelim 
                   6894:       nstepm is the number of stepm from age to agelim. 
                   6895:       Look at function hpijx to understand why because of memory size limitations, 
                   6896:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6897:       survival function given by stepm (the optimization length). Unfortunately it
                   6898:       means that if the survival funtion is printed every two years of age and if
                   6899:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6900:       results. So we changed our mind and took the option of the best precision.
                   6901:    */
                   6902:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6903:    agelim = AGESUP;
                   6904:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6905:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6906:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6907:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6908:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6909:      gp=matrix(0,nhstepm,1,nlstate);
                   6910:      gm=matrix(0,nhstepm,1,nlstate);
                   6911:                
                   6912:                
                   6913:      for(theta=1; theta <=npar; theta++){
                   6914:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6915:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6916:        }
1.279     brouard  6917:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6918:        * returns into prlim .
1.288     brouard  6919:        */
1.242     brouard  6920:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6921: 
                   6922:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6923:        if (popbased==1) {
                   6924:         if(mobilav ==0){
                   6925:           for(i=1; i<=nlstate;i++)
                   6926:             prlim[i][i]=probs[(int)age][i][ij];
                   6927:         }else{ /* mobilav */ 
                   6928:           for(i=1; i<=nlstate;i++)
                   6929:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6930:         }
                   6931:        }
1.295     brouard  6932:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6933:        */                      
                   6934:        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  6935:        /**< 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  6936:        * at horizon h in state j including mortality.
                   6937:        */
1.218     brouard  6938:        for(j=1; j<= nlstate; j++){
                   6939:         for(h=0; h<=nhstepm; h++){
                   6940:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6941:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6942:         }
                   6943:        }
1.279     brouard  6944:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6945:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6946:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6947:        */
                   6948:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6949:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6950:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6951:        }
                   6952:        
                   6953:        /* Again with minus shift */
1.218     brouard  6954:                        
                   6955:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6956:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6957: 
1.242     brouard  6958:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6959:                        
                   6960:        if (popbased==1) {
                   6961:         if(mobilav ==0){
                   6962:           for(i=1; i<=nlstate;i++)
                   6963:             prlim[i][i]=probs[(int)age][i][ij];
                   6964:         }else{ /* mobilav */ 
                   6965:           for(i=1; i<=nlstate;i++)
                   6966:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6967:         }
                   6968:        }
                   6969:                        
1.235     brouard  6970:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6971:                        
                   6972:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6973:         for(h=0; h<=nhstepm; h++){
                   6974:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6975:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6976:         }
                   6977:        }
                   6978:        /* This for computing probability of death (h=1 means
                   6979:          computed over hstepm matrices product = hstepm*stepm months) 
                   6980:          as a weighted average of prlim.
                   6981:        */
                   6982:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6983:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6984:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6985:        }    
1.279     brouard  6986:        /* end shifting computations */
                   6987: 
                   6988:        /**< Computing gradient matrix at horizon h 
                   6989:        */
1.218     brouard  6990:        for(j=1; j<= nlstate; j++) /* vareij */
                   6991:         for(h=0; h<=nhstepm; h++){
                   6992:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6993:         }
1.279     brouard  6994:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6995:        */
                   6996:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6997:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6998:        }
                   6999:                        
                   7000:      } /* End theta */
1.279     brouard  7001:      
                   7002:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7003:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7004:                
                   7005:      for(h=0; h<=nhstepm; h++) /* veij */
                   7006:        for(j=1; j<=nlstate;j++)
                   7007:         for(theta=1; theta <=npar; theta++)
                   7008:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7009:                
                   7010:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7011:        for(theta=1; theta <=npar; theta++)
                   7012:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7013:      /**< as well as its transposed matrix 
                   7014:       */               
1.218     brouard  7015:                
                   7016:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7017:      for(i=1;i<=nlstate;i++)
                   7018:        for(j=1;j<=nlstate;j++)
                   7019:         vareij[i][j][(int)age] =0.;
1.279     brouard  7020: 
                   7021:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7022:       * and k (nhstepm) formula 15 of article
                   7023:       * Lievre-Brouard-Heathcote
                   7024:       */
                   7025:      
1.218     brouard  7026:      for(h=0;h<=nhstepm;h++){
                   7027:        for(k=0;k<=nhstepm;k++){
                   7028:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7029:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7030:         for(i=1;i<=nlstate;i++)
                   7031:           for(j=1;j<=nlstate;j++)
                   7032:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7033:        }
                   7034:      }
                   7035:                
1.279     brouard  7036:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7037:       * p.j overall mortality formula 49 but computed directly because
                   7038:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7039:       * wix is independent of theta.
                   7040:       */
1.218     brouard  7041:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7042:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7043:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7044:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7045:         varppt[j][i]=doldmp[j][i];
                   7046:      /* end ppptj */
                   7047:      /*  x centered again */
                   7048:                
1.242     brouard  7049:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7050:                
                   7051:      if (popbased==1) {
                   7052:        if(mobilav ==0){
                   7053:         for(i=1; i<=nlstate;i++)
                   7054:           prlim[i][i]=probs[(int)age][i][ij];
                   7055:        }else{ /* mobilav */ 
                   7056:         for(i=1; i<=nlstate;i++)
                   7057:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7058:        }
                   7059:      }
                   7060:                
                   7061:      /* This for computing probability of death (h=1 means
                   7062:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7063:        as a weighted average of prlim.
                   7064:      */
1.235     brouard  7065:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7066:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7067:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7068:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7069:      }    
                   7070:      /* end probability of death */
                   7071:                
                   7072:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7073:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7074:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7075:        for(i=1; i<=nlstate;i++){
                   7076:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7077:        }
                   7078:      } 
                   7079:      fprintf(ficresprobmorprev,"\n");
                   7080:                
                   7081:      fprintf(ficresvij,"%.0f ",age );
                   7082:      for(i=1; i<=nlstate;i++)
                   7083:        for(j=1; j<=nlstate;j++){
                   7084:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7085:        }
                   7086:      fprintf(ficresvij,"\n");
                   7087:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7088:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7089:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7090:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7091:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7092:    } /* End age */
                   7093:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7094:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7095:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7096:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7097:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7098:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7099:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7100:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7101:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7102:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7103:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7104:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7105:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7106:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7107:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7108:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7109:    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);
                   7110:    /*  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  7111:     */
1.218     brouard  7112:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7113:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7114: 
1.218     brouard  7115:    free_vector(xp,1,npar);
                   7116:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7117:    free_matrix(dnewm,1,nlstate,1,npar);
                   7118:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7119:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7120:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7121:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7122:    fclose(ficresprobmorprev);
                   7123:    fflush(ficgp);
                   7124:    fflush(fichtm); 
                   7125:  }  /* end varevsij */
1.126     brouard  7126: 
                   7127: /************ Variance of prevlim ******************/
1.269     brouard  7128:  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  7129: {
1.205     brouard  7130:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7131:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7132: 
1.268     brouard  7133:   double **dnewmpar,**doldm;
1.126     brouard  7134:   int i, j, nhstepm, hstepm;
                   7135:   double *xp;
                   7136:   double *gp, *gm;
                   7137:   double **gradg, **trgradg;
1.208     brouard  7138:   double **mgm, **mgp;
1.126     brouard  7139:   double age,agelim;
                   7140:   int theta;
                   7141:   
                   7142:   pstamp(ficresvpl);
1.288     brouard  7143:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7144:   fprintf(ficresvpl,"# Age ");
                   7145:   if(nresult >=1)
                   7146:     fprintf(ficresvpl," Result# ");
1.126     brouard  7147:   for(i=1; i<=nlstate;i++)
                   7148:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7149:   fprintf(ficresvpl,"\n");
                   7150: 
                   7151:   xp=vector(1,npar);
1.268     brouard  7152:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7153:   doldm=matrix(1,nlstate,1,nlstate);
                   7154:   
                   7155:   hstepm=1*YEARM; /* Every year of age */
                   7156:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7157:   agelim = AGESUP;
                   7158:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7159:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7160:     if (stepm >= YEARM) hstepm=1;
                   7161:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7162:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7163:     mgp=matrix(1,npar,1,nlstate);
                   7164:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7165:     gp=vector(1,nlstate);
                   7166:     gm=vector(1,nlstate);
                   7167: 
                   7168:     for(theta=1; theta <=npar; theta++){
                   7169:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7170:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7171:       }
1.288     brouard  7172:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7173:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7174:       /* else */
                   7175:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7176:       for(i=1;i<=nlstate;i++){
1.126     brouard  7177:        gp[i] = prlim[i][i];
1.208     brouard  7178:        mgp[theta][i] = prlim[i][i];
                   7179:       }
1.126     brouard  7180:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7181:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7182:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7183:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7184:       /* else */
                   7185:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7186:       for(i=1;i<=nlstate;i++){
1.126     brouard  7187:        gm[i] = prlim[i][i];
1.208     brouard  7188:        mgm[theta][i] = prlim[i][i];
                   7189:       }
1.126     brouard  7190:       for(i=1;i<=nlstate;i++)
                   7191:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7192:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7193:     } /* End theta */
                   7194: 
                   7195:     trgradg =matrix(1,nlstate,1,npar);
                   7196: 
                   7197:     for(j=1; j<=nlstate;j++)
                   7198:       for(theta=1; theta <=npar; theta++)
                   7199:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7200:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7201:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7202:     /*   for(j=1; j<=nlstate;j++){ */
                   7203:     /*         printf(" %d ",j); */
                   7204:     /*         for(theta=1; theta <=npar; theta++) */
                   7205:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7206:     /*         printf("\n "); */
                   7207:     /*   } */
                   7208:     /* } */
                   7209:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7210:     /*   printf("\n gradg %d ",(int)age); */
                   7211:     /*   for(j=1; j<=nlstate;j++){ */
                   7212:     /*         printf("%d ",j); */
                   7213:     /*         for(theta=1; theta <=npar; theta++) */
                   7214:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7215:     /*         printf("\n "); */
                   7216:     /*   } */
                   7217:     /* } */
1.126     brouard  7218: 
                   7219:     for(i=1;i<=nlstate;i++)
                   7220:       varpl[i][(int)age] =0.;
1.209     brouard  7221:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7222:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7223:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7224:     }else{
1.268     brouard  7225:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7226:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7227:     }
1.126     brouard  7228:     for(i=1;i<=nlstate;i++)
                   7229:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7230: 
                   7231:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7232:     if(nresult >=1)
                   7233:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7234:     for(i=1; i<=nlstate;i++){
1.126     brouard  7235:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7236:       /* for(j=1;j<=nlstate;j++) */
                   7237:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7238:     }
1.126     brouard  7239:     fprintf(ficresvpl,"\n");
                   7240:     free_vector(gp,1,nlstate);
                   7241:     free_vector(gm,1,nlstate);
1.208     brouard  7242:     free_matrix(mgm,1,npar,1,nlstate);
                   7243:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7244:     free_matrix(gradg,1,npar,1,nlstate);
                   7245:     free_matrix(trgradg,1,nlstate,1,npar);
                   7246:   } /* End age */
                   7247: 
                   7248:   free_vector(xp,1,npar);
                   7249:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7250:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7251: 
                   7252: }
                   7253: 
                   7254: 
                   7255: /************ Variance of backprevalence limit ******************/
1.269     brouard  7256:  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  7257: {
                   7258:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7259:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7260: 
                   7261:   double **dnewmpar,**doldm;
                   7262:   int i, j, nhstepm, hstepm;
                   7263:   double *xp;
                   7264:   double *gp, *gm;
                   7265:   double **gradg, **trgradg;
                   7266:   double **mgm, **mgp;
                   7267:   double age,agelim;
                   7268:   int theta;
                   7269:   
                   7270:   pstamp(ficresvbl);
                   7271:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7272:   fprintf(ficresvbl,"# Age ");
                   7273:   if(nresult >=1)
                   7274:     fprintf(ficresvbl," Result# ");
                   7275:   for(i=1; i<=nlstate;i++)
                   7276:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7277:   fprintf(ficresvbl,"\n");
                   7278: 
                   7279:   xp=vector(1,npar);
                   7280:   dnewmpar=matrix(1,nlstate,1,npar);
                   7281:   doldm=matrix(1,nlstate,1,nlstate);
                   7282:   
                   7283:   hstepm=1*YEARM; /* Every year of age */
                   7284:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7285:   agelim = AGEINF;
                   7286:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7287:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7288:     if (stepm >= YEARM) hstepm=1;
                   7289:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7290:     gradg=matrix(1,npar,1,nlstate);
                   7291:     mgp=matrix(1,npar,1,nlstate);
                   7292:     mgm=matrix(1,npar,1,nlstate);
                   7293:     gp=vector(1,nlstate);
                   7294:     gm=vector(1,nlstate);
                   7295: 
                   7296:     for(theta=1; theta <=npar; theta++){
                   7297:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7298:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7299:       }
                   7300:       if(mobilavproj > 0 )
                   7301:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7302:       else
                   7303:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7304:       for(i=1;i<=nlstate;i++){
                   7305:        gp[i] = bprlim[i][i];
                   7306:        mgp[theta][i] = bprlim[i][i];
                   7307:       }
                   7308:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7309:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7310:        if(mobilavproj > 0 )
                   7311:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7312:        else
                   7313:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7314:       for(i=1;i<=nlstate;i++){
                   7315:        gm[i] = bprlim[i][i];
                   7316:        mgm[theta][i] = bprlim[i][i];
                   7317:       }
                   7318:       for(i=1;i<=nlstate;i++)
                   7319:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7320:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7321:     } /* End theta */
                   7322: 
                   7323:     trgradg =matrix(1,nlstate,1,npar);
                   7324: 
                   7325:     for(j=1; j<=nlstate;j++)
                   7326:       for(theta=1; theta <=npar; theta++)
                   7327:        trgradg[j][theta]=gradg[theta][j];
                   7328:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7329:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7330:     /*   for(j=1; j<=nlstate;j++){ */
                   7331:     /*         printf(" %d ",j); */
                   7332:     /*         for(theta=1; theta <=npar; theta++) */
                   7333:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7334:     /*         printf("\n "); */
                   7335:     /*   } */
                   7336:     /* } */
                   7337:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7338:     /*   printf("\n gradg %d ",(int)age); */
                   7339:     /*   for(j=1; j<=nlstate;j++){ */
                   7340:     /*         printf("%d ",j); */
                   7341:     /*         for(theta=1; theta <=npar; theta++) */
                   7342:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7343:     /*         printf("\n "); */
                   7344:     /*   } */
                   7345:     /* } */
                   7346: 
                   7347:     for(i=1;i<=nlstate;i++)
                   7348:       varbpl[i][(int)age] =0.;
                   7349:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7350:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7351:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7352:     }else{
                   7353:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7354:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7355:     }
                   7356:     for(i=1;i<=nlstate;i++)
                   7357:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7358: 
                   7359:     fprintf(ficresvbl,"%.0f ",age );
                   7360:     if(nresult >=1)
                   7361:       fprintf(ficresvbl,"%d ",nres );
                   7362:     for(i=1; i<=nlstate;i++)
                   7363:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7364:     fprintf(ficresvbl,"\n");
                   7365:     free_vector(gp,1,nlstate);
                   7366:     free_vector(gm,1,nlstate);
                   7367:     free_matrix(mgm,1,npar,1,nlstate);
                   7368:     free_matrix(mgp,1,npar,1,nlstate);
                   7369:     free_matrix(gradg,1,npar,1,nlstate);
                   7370:     free_matrix(trgradg,1,nlstate,1,npar);
                   7371:   } /* End age */
                   7372: 
                   7373:   free_vector(xp,1,npar);
                   7374:   free_matrix(doldm,1,nlstate,1,npar);
                   7375:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7376: 
                   7377: }
                   7378: 
                   7379: /************ Variance of one-step probabilities  ******************/
                   7380: 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  7381:  {
                   7382:    int i, j=0,  k1, l1, tj;
                   7383:    int k2, l2, j1,  z1;
                   7384:    int k=0, l;
                   7385:    int first=1, first1, first2;
1.326     brouard  7386:    int nres=0; /* New */
1.222     brouard  7387:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7388:    double **dnewm,**doldm;
                   7389:    double *xp;
                   7390:    double *gp, *gm;
                   7391:    double **gradg, **trgradg;
                   7392:    double **mu;
                   7393:    double age, cov[NCOVMAX+1];
                   7394:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7395:    int theta;
                   7396:    char fileresprob[FILENAMELENGTH];
                   7397:    char fileresprobcov[FILENAMELENGTH];
                   7398:    char fileresprobcor[FILENAMELENGTH];
                   7399:    double ***varpij;
                   7400: 
                   7401:    strcpy(fileresprob,"PROB_"); 
                   7402:    strcat(fileresprob,fileres);
                   7403:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7404:      printf("Problem with resultfile: %s\n", fileresprob);
                   7405:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7406:    }
                   7407:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7408:    strcat(fileresprobcov,fileresu);
                   7409:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7410:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7411:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7412:    }
                   7413:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7414:    strcat(fileresprobcor,fileresu);
                   7415:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7416:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7417:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7418:    }
                   7419:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7420:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7421:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7422:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7423:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7424:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7425:    pstamp(ficresprob);
                   7426:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7427:    fprintf(ficresprob,"# Age");
                   7428:    pstamp(ficresprobcov);
                   7429:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7430:    fprintf(ficresprobcov,"# Age");
                   7431:    pstamp(ficresprobcor);
                   7432:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7433:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7434: 
                   7435: 
1.222     brouard  7436:    for(i=1; i<=nlstate;i++)
                   7437:      for(j=1; j<=(nlstate+ndeath);j++){
                   7438:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7439:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7440:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7441:      }  
                   7442:    /* fprintf(ficresprob,"\n");
                   7443:       fprintf(ficresprobcov,"\n");
                   7444:       fprintf(ficresprobcor,"\n");
                   7445:    */
                   7446:    xp=vector(1,npar);
                   7447:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7448:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7449:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7450:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7451:    first=1;
                   7452:    fprintf(ficgp,"\n# Routine varprob");
                   7453:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7454:    fprintf(fichtm,"\n");
                   7455: 
1.288     brouard  7456:    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  7457:    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);
                   7458:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7459: and drawn. It helps understanding how is the covariance between two incidences.\
                   7460:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7461:    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  7462: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7463: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7464: standard deviations wide on each axis. <br>\
                   7465:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7466:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7467: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7468: 
1.222     brouard  7469:    cov[1]=1;
                   7470:    /* tj=cptcoveff; */
1.225     brouard  7471:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7472:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7473:    j1=0;
1.332     brouard  7474: 
                   7475:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7476:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7477:      /* 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  7478:      if(tj != 1 && TKresult[nres]!= j1)
                   7479:        continue;
                   7480: 
                   7481:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7482:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7483:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7484:      if  (cptcovn>0) {
1.334     brouard  7485:        fprintf(ficresprob, "\n#********** Variable ");
                   7486:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7487:        fprintf(ficgp, "\n#********** Variable ");
                   7488:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7489:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7490: 
                   7491:        /* Including quantitative variables of the resultline to be done */
                   7492:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7493:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7494:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7495:         /* 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  7496:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7497:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7498:             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  */
                   7499:             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  */
                   7500:             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  */
                   7501:             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  */
                   7502:             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  */
                   7503:             fprintf(ficresprob,"fixed ");
                   7504:             fprintf(ficresprobcov,"fixed ");
                   7505:             fprintf(ficgp,"fixed ");
                   7506:             fprintf(fichtmcov,"fixed ");
                   7507:             fprintf(ficresprobcor,"fixed ");
                   7508:           }else{
                   7509:             fprintf(ficresprob,"varyi ");
                   7510:             fprintf(ficresprobcov,"varyi ");
                   7511:             fprintf(ficgp,"varyi ");
                   7512:             fprintf(fichtmcov,"varyi ");
                   7513:             fprintf(ficresprobcor,"varyi ");
                   7514:           }
                   7515:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7516:           /* For each selected (single) quantitative value */
1.337     brouard  7517:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7518:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7519:             fprintf(ficresprob,"fixed ");
                   7520:             fprintf(ficresprobcov,"fixed ");
                   7521:             fprintf(ficgp,"fixed ");
                   7522:             fprintf(fichtmcov,"fixed ");
                   7523:             fprintf(ficresprobcor,"fixed ");
                   7524:           }else{
                   7525:             fprintf(ficresprob,"varyi ");
                   7526:             fprintf(ficresprobcov,"varyi ");
                   7527:             fprintf(ficgp,"varyi ");
                   7528:             fprintf(fichtmcov,"varyi ");
                   7529:             fprintf(ficresprobcor,"varyi ");
                   7530:           }
                   7531:         }else{
                   7532:           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 */
                   7533:           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 */
                   7534:           exit(1);
                   7535:         }
                   7536:        } /* End loop on variable of this resultline */
                   7537:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7538:        fprintf(ficresprob, "**********\n#\n");
                   7539:        fprintf(ficresprobcov, "**********\n#\n");
                   7540:        fprintf(ficgp, "**********\n#\n");
                   7541:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7542:        fprintf(ficresprobcor, "**********\n#");    
                   7543:        if(invalidvarcomb[j1]){
                   7544:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7545:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7546:         continue;
                   7547:        }
                   7548:      }
                   7549:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7550:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7551:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7552:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7553:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7554:        cov[2]=age;
                   7555:        if(nagesqr==1)
                   7556:         cov[3]= age*age;
1.334     brouard  7557:        /* New code end of combination but for each resultline */
                   7558:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7559:         if(Typevar[k1]==1){ /* A product with age */
                   7560:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7561:         }else{
1.334     brouard  7562:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7563:         }
1.334     brouard  7564:        }/* End of loop on model equation */
                   7565: /* Old code */
                   7566:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7567:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7568:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7569:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7570:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7571:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7572:        /*                                                                  * 1  1 1 1 1 */
                   7573:        /*                                                                  * 2  2 1 1 1 */
                   7574:        /*                                                                  * 3  1 2 1 1 */
                   7575:        /*                                                                  *\/ */
                   7576:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7577:        /* } */
                   7578:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7579:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7580:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7581:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7582:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7583:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7584:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7585:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7586:        /*         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]); */
                   7587:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7588:        /*         /\* exit(1); *\/ */
                   7589:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7590:        /*       } */
                   7591:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7592:        /* } */
                   7593:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7594:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7595:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7596:        /*           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]])]; */
                   7597:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7598:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7599:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7600:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7601:        /*         } */
                   7602:        /*       }else{ */
                   7603:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7604:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7605:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7606:        /*         }else{ */
                   7607:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7608:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7609:        /*         } */
                   7610:        /*       } */
                   7611:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7612:        /* } */                 
1.326     brouard  7613: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7614:        for(theta=1; theta <=npar; theta++){
                   7615:         for(i=1; i<=npar; i++)
                   7616:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7617:                                
1.222     brouard  7618:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7619:                                
1.222     brouard  7620:         k=0;
                   7621:         for(i=1; i<= (nlstate); i++){
                   7622:           for(j=1; j<=(nlstate+ndeath);j++){
                   7623:             k=k+1;
                   7624:             gp[k]=pmmij[i][j];
                   7625:           }
                   7626:         }
1.220     brouard  7627:                                
1.222     brouard  7628:         for(i=1; i<=npar; i++)
                   7629:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7630:                                
1.222     brouard  7631:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7632:         k=0;
                   7633:         for(i=1; i<=(nlstate); i++){
                   7634:           for(j=1; j<=(nlstate+ndeath);j++){
                   7635:             k=k+1;
                   7636:             gm[k]=pmmij[i][j];
                   7637:           }
                   7638:         }
1.220     brouard  7639:                                
1.222     brouard  7640:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7641:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7642:        }
1.126     brouard  7643: 
1.222     brouard  7644:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7645:         for(theta=1; theta <=npar; theta++)
                   7646:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7647:                        
1.222     brouard  7648:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7649:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7650:                        
1.222     brouard  7651:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7652:                        
1.222     brouard  7653:        k=0;
                   7654:        for(i=1; i<=(nlstate); i++){
                   7655:         for(j=1; j<=(nlstate+ndeath);j++){
                   7656:           k=k+1;
                   7657:           mu[k][(int) age]=pmmij[i][j];
                   7658:         }
                   7659:        }
                   7660:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7661:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7662:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7663:                        
1.222     brouard  7664:        /*printf("\n%d ",(int)age);
                   7665:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7666:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7667:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7668:         }*/
1.220     brouard  7669:                        
1.222     brouard  7670:        fprintf(ficresprob,"\n%d ",(int)age);
                   7671:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7672:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7673:                        
1.222     brouard  7674:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7675:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7676:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7677:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7678:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7679:        }
                   7680:        i=0;
                   7681:        for (k=1; k<=(nlstate);k++){
                   7682:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7683:           i++;
                   7684:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7685:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7686:           for (j=1; j<=i;j++){
                   7687:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7688:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7689:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7690:           }
                   7691:         }
                   7692:        }/* end of loop for state */
                   7693:      } /* end of loop for age */
                   7694:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7695:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7696:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7697:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7698:     
                   7699:      /* Confidence intervalle of pij  */
                   7700:      /*
                   7701:        fprintf(ficgp,"\nunset parametric;unset label");
                   7702:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7703:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7704:        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);
                   7705:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7706:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7707:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7708:      */
                   7709:                
                   7710:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7711:      first1=1;first2=2;
                   7712:      for (k2=1; k2<=(nlstate);k2++){
                   7713:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7714:         if(l2==k2) continue;
                   7715:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7716:         for (k1=1; k1<=(nlstate);k1++){
                   7717:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7718:             if(l1==k1) continue;
                   7719:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7720:             if(i<=j) continue;
                   7721:             for (age=bage; age<=fage; age ++){ 
                   7722:               if ((int)age %5==0){
                   7723:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7724:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7725:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7726:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7727:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7728:                 c12=cv12/sqrt(v1*v2);
                   7729:                 /* Computing eigen value of matrix of covariance */
                   7730:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7731:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7732:                 if ((lc2 <0) || (lc1 <0) ){
                   7733:                   if(first2==1){
                   7734:                     first1=0;
                   7735:                     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);
                   7736:                   }
                   7737:                   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);
                   7738:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7739:                   /* lc2=fabs(lc2); */
                   7740:                 }
1.220     brouard  7741:                                                                
1.222     brouard  7742:                 /* Eigen vectors */
1.280     brouard  7743:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7744:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7745:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7746:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7747:                 }else
                   7748:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7749:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7750:                 v21=(lc1-v1)/cv12*v11;
                   7751:                 v12=-v21;
                   7752:                 v22=v11;
                   7753:                 tnalp=v21/v11;
                   7754:                 if(first1==1){
                   7755:                   first1=0;
                   7756:                   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);
                   7757:                 }
                   7758:                 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);
                   7759:                 /*printf(fignu*/
                   7760:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7761:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7762:                 if(first==1){
                   7763:                   first=0;
                   7764:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7765:                   fprintf(ficgp,"\nset parametric;unset label");
                   7766:                   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);
                   7767:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7768:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7769:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7770: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7771:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7772:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7773:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7774:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7775:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7776:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7777:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7778:                   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  7779:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7780:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7781:                 }else{
                   7782:                   first=0;
                   7783:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7784:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7785:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7786:                   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  7787:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7788:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7789:                 }/* if first */
                   7790:               } /* age mod 5 */
                   7791:             } /* end loop age */
                   7792:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7793:             first=1;
                   7794:           } /*l12 */
                   7795:         } /* k12 */
                   7796:        } /*l1 */
                   7797:      }/* k1 */
1.332     brouard  7798:    }  /* loop on combination of covariates j1 */
1.326     brouard  7799:    } /* loop on nres */
1.222     brouard  7800:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7801:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7802:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7803:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7804:    free_vector(xp,1,npar);
                   7805:    fclose(ficresprob);
                   7806:    fclose(ficresprobcov);
                   7807:    fclose(ficresprobcor);
                   7808:    fflush(ficgp);
                   7809:    fflush(fichtmcov);
                   7810:  }
1.126     brouard  7811: 
                   7812: 
                   7813: /******************* Printing html file ***********/
1.201     brouard  7814: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7815:                  int lastpass, int stepm, int weightopt, char model[],\
                   7816:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7817:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7818:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7819:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7820:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7821:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7822:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7823:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7824: </ul>");
1.319     brouard  7825: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7826: /* </ul>", model); */
1.214     brouard  7827:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7828:    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",
                   7829:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7830:    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  7831:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7832:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7833:    fprintf(fichtm,"\
                   7834:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7835:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7836:    fprintf(fichtm,"\
1.217     brouard  7837:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7838:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7839:    fprintf(fichtm,"\
1.288     brouard  7840:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7841:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7842:    fprintf(fichtm,"\
1.288     brouard  7843:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7844:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7845:    fprintf(fichtm,"\
1.211     brouard  7846:  - (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  7847:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7848:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7849:    if(prevfcast==1){
                   7850:      fprintf(fichtm,"\
                   7851:  - Prevalence projections by age and states:                           \
1.201     brouard  7852:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7853:    }
1.126     brouard  7854: 
                   7855: 
1.225     brouard  7856:    m=pow(2,cptcoveff);
1.222     brouard  7857:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7858: 
1.317     brouard  7859:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7860: 
                   7861:    jj1=0;
                   7862: 
                   7863:    fprintf(fichtm," \n<ul>");
1.337     brouard  7864:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7865:      /* k1=nres; */
1.338     brouard  7866:      k1=TKresult[nres];
                   7867:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7868:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7869:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7870:    /*     continue; */
1.264     brouard  7871:      jj1++;
                   7872:      if (cptcovn > 0) {
                   7873:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7874:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7875:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7876:        }
1.337     brouard  7877:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7878:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7879:        /* } */
                   7880:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7881:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7882:        /* } */
1.264     brouard  7883:        fprintf(fichtm,"\">");
                   7884:        
                   7885:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7886:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7887:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7888:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7889:        }
1.337     brouard  7890:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7891:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7892:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7893:        /* } */
                   7894:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7895:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7896:        /* } */
1.264     brouard  7897:        if(invalidvarcomb[k1]){
                   7898:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7899:         continue;
                   7900:        }
                   7901:        fprintf(fichtm,"</a></li>");
                   7902:      } /* cptcovn >0 */
                   7903:    }
1.317     brouard  7904:    fprintf(fichtm," \n</ul>");
1.264     brouard  7905: 
1.222     brouard  7906:    jj1=0;
1.237     brouard  7907: 
1.337     brouard  7908:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7909:      /* k1=nres; */
1.338     brouard  7910:      k1=TKresult[nres];
                   7911:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7912:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7913:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7914:    /*     continue; */
1.220     brouard  7915: 
1.222     brouard  7916:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7917:      jj1++;
                   7918:      if (cptcovn > 0) {
1.264     brouard  7919:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7920:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7921:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7922:        }
1.337     brouard  7923:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7924:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7925:        /* } */
1.264     brouard  7926:        fprintf(fichtm,"\"</a>");
                   7927:  
1.222     brouard  7928:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7929:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7930:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7931:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7932:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7933:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7934:        }
1.230     brouard  7935:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7936:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7937:        if(invalidvarcomb[k1]){
                   7938:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7939:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7940:         continue;
                   7941:        }
                   7942:      }
                   7943:      /* aij, bij */
1.259     brouard  7944:      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  7945: <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  7946:      /* Pij */
1.241     brouard  7947:      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> \
                   7948: <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  7949:      /* Quasi-incidences */
                   7950:      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  7951:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7952:  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  7953: 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> \
                   7954: <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  7955:      /* Survival functions (period) in state j */
                   7956:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7957:        fprintf(fichtm,"<br>\n- Survival functions in state %d. And probability to be observed in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   7958:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7959:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7960:      }
                   7961:      /* State specific survival functions (period) */
                   7962:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7963:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7964:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7965:  <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);
                   7966:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7967:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7968:      }
1.288     brouard  7969:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7970:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7971:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability for a person being in state (1 to %d) at different ages, to be in state %d some years after. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.338     brouard  7972:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7973:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7974:      }
1.296     brouard  7975:      if(prevbcast==1){
1.288     brouard  7976:        /* Backward prevalence in each health state */
1.222     brouard  7977:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7978:         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);
                   7979:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7980:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7981:        }
1.217     brouard  7982:      }
1.222     brouard  7983:      if(prevfcast==1){
1.288     brouard  7984:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7985:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7986:         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);
                   7987:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7988:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7989:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7990:        }
                   7991:      }
1.296     brouard  7992:      if(prevbcast==1){
1.268     brouard  7993:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7994:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7995:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7996:  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 \
                   7997:  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  7998: 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);
                   7999:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8000:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8001:        }
                   8002:      }
1.220     brouard  8003:         
1.222     brouard  8004:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8005:        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);
                   8006:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8007:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8008:      }
                   8009:      /* } /\* end i1 *\/ */
1.337     brouard  8010:    }/* End k1=nres */
1.222     brouard  8011:    fprintf(fichtm,"</ul>");
1.126     brouard  8012: 
1.222     brouard  8013:    fprintf(fichtm,"\
1.126     brouard  8014: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8015:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8016:  - 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  8017: But because parameters are usually highly correlated (a higher incidence of disability \
                   8018: and a higher incidence of recovery can give very close observed transition) it might \
                   8019: be very useful to look not only at linear confidence intervals estimated from the \
                   8020: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8021: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8022: covariance matrix of the one-step probabilities. \
                   8023: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8024: 
1.222     brouard  8025:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8026:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8027:    fprintf(fichtm,"\
1.126     brouard  8028:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8029:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8030: 
1.222     brouard  8031:    fprintf(fichtm,"\
1.126     brouard  8032:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8033:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8034:    fprintf(fichtm,"\
1.126     brouard  8035:  - 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): \
                   8036:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8037:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8038:    fprintf(fichtm,"\
1.126     brouard  8039:  - (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): \
                   8040:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8041:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8042:    fprintf(fichtm,"\
1.288     brouard  8043:  - 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  8044:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8045:    fprintf(fichtm,"\
1.128     brouard  8046:  - 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  8047:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8048:    fprintf(fichtm,"\
1.288     brouard  8049:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8050:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8051: 
                   8052: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8053: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8054: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8055: /*     <br>",fileres,fileres,fileres,fileres); */
                   8056: /*  else  */
1.338     brouard  8057: /*    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  8058:    fflush(fichtm);
1.126     brouard  8059: 
1.225     brouard  8060:    m=pow(2,cptcoveff);
1.222     brouard  8061:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8062: 
1.317     brouard  8063:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8064: 
                   8065:   jj1=0;
                   8066: 
                   8067:    fprintf(fichtm," \n<ul>");
1.337     brouard  8068:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8069:      /* k1=nres; */
1.338     brouard  8070:      k1=TKresult[nres];
1.337     brouard  8071:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8072:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8073:      /*   continue; */
1.317     brouard  8074:      jj1++;
                   8075:      if (cptcovn > 0) {
                   8076:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8077:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8078:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8079:        }
                   8080:        fprintf(fichtm,"\">");
                   8081:        
                   8082:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8083:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8084:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8085:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8086:        }
                   8087:        if(invalidvarcomb[k1]){
                   8088:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8089:         continue;
                   8090:        }
                   8091:        fprintf(fichtm,"</a></li>");
                   8092:      } /* cptcovn >0 */
1.337     brouard  8093:    } /* End nres */
1.317     brouard  8094:    fprintf(fichtm," \n</ul>");
                   8095: 
1.222     brouard  8096:    jj1=0;
1.237     brouard  8097: 
1.241     brouard  8098:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8099:      /* k1=nres; */
1.338     brouard  8100:      k1=TKresult[nres];
                   8101:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8102:      /* for(k1=1; k1<=m;k1++){ */
                   8103:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8104:      /*   continue; */
1.222     brouard  8105:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8106:      jj1++;
1.126     brouard  8107:      if (cptcovn > 0) {
1.317     brouard  8108:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8109:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8110:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8111:        }
                   8112:        fprintf(fichtm,"\"</a>");
                   8113:        
1.126     brouard  8114:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8115:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8116:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8117:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8118:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8119:        }
1.237     brouard  8120: 
1.338     brouard  8121:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8122: 
1.222     brouard  8123:        if(invalidvarcomb[k1]){
                   8124:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8125:         continue;
                   8126:        }
1.337     brouard  8127:      } /* If cptcovn >0 */
1.126     brouard  8128:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8129:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8130: 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);
                   8131:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8132:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8133:      }
                   8134:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8135: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8136: true period expectancies (those weighted with period prevalences are also\
                   8137:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8138:  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);
                   8139:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8140:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8141:      /* } /\* end i1 *\/ */
1.241     brouard  8142:   }/* End nres */
1.222     brouard  8143:    fprintf(fichtm,"</ul>");
                   8144:    fflush(fichtm);
1.126     brouard  8145: }
                   8146: 
                   8147: /******************* Gnuplot file **************/
1.296     brouard  8148: 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  8149: 
                   8150:   char dirfileres[132],optfileres[132];
1.264     brouard  8151:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8152:   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  8153:   int lv=0, vlv=0, kl=0;
1.130     brouard  8154:   int ng=0;
1.201     brouard  8155:   int vpopbased;
1.223     brouard  8156:   int ioffset; /* variable offset for columns */
1.270     brouard  8157:   int iyearc=1; /* variable column for year of projection  */
                   8158:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8159:   int nres=0; /* Index of resultline */
1.266     brouard  8160:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8161: 
1.126     brouard  8162: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8163: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8164: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8165: /*   } */
                   8166: 
                   8167:   /*#ifdef windows */
                   8168:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8169:   /*#endif */
1.225     brouard  8170:   m=pow(2,cptcoveff);
1.126     brouard  8171: 
1.274     brouard  8172:   /* diagram of the model */
                   8173:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8174:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8175:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8176:   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);
                   8177: 
1.343     brouard  8178:   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  8179:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8180:   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);
                   8181:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8182:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8183:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8184:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8185: 
1.202     brouard  8186:   /* Contribution to likelihood */
                   8187:   /* Plot the probability implied in the likelihood */
1.223     brouard  8188:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8189:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8190:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8191:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8192: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8193:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8194: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8195:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8196:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8197:   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));
                   8198:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8199:   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));
                   8200:   for (i=1; i<= nlstate ; i ++) {
                   8201:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8202:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8203:     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);
                   8204:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8205:       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);
                   8206:     }
                   8207:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8208:   }
                   8209:   /* 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 */               
                   8210:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8211:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8212:   fprintf(ficgp,"\nset out;unset log\n");
                   8213:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8214: 
1.343     brouard  8215:   /* Plot the probability implied in the likelihood by covariate value */
                   8216:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8217:   /* if(debugILK==1){ */
                   8218:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   8219:     kvar=Tvar[TvarFind[kf]]; /* variable */
                   8220:     k=18+Tvar[TvarFind[kf]];/*offset because there are 18 columns in the ILK_ file */
                   8221:     for (i=1; i<= nlstate ; i ++) {
                   8222:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8223:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8224:       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);
                   8225:       for (j=2; j<= nlstate+ndeath ; j ++) {
                   8226:        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);
                   8227:       }
                   8228:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8229:     }
                   8230:   } /* End of each covariate dummy */
                   8231:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8232:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8233:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8234:      *  varying                   1     2                                 3       4        5
                   8235:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8236:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8237:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8238:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8239:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8240:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8241:      */
                   8242:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8243:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8244:     /* 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]); */
                   8245:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8246:       /* printf(" %d",ipos); */
                   8247:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8248:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8249:       kk++; /* Position of the ncovv column in ILK_ */
                   8250:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8251:       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)  */
                   8252:        for (i=1; i<= nlstate ; i ++) {
                   8253:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8254:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8255: 
                   8256:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8257:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8258:            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);
                   8259:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8260:              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);
                   8261:            }
                   8262:          }else{
                   8263:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8264:            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);
                   8265:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8266:              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);
                   8267:            }
                   8268:          }
                   8269:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8270:        }
                   8271:       }/* End if dummy varying */
                   8272:     }else{ /*Product */
                   8273:       /* printf("*"); */
                   8274:       /* fprintf(ficresilk,"*"); */
                   8275:     }
                   8276:     iposold=ipos;
                   8277:   } /* For each time varying covariate */
                   8278:   /* } /\* debugILK==1 *\/ */
                   8279:   /* 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 */               
                   8280:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8281:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8282:   fprintf(ficgp,"\nset out;unset log\n");
                   8283:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8284: 
                   8285: 
                   8286:   
1.126     brouard  8287:   strcpy(dirfileres,optionfilefiname);
                   8288:   strcpy(optfileres,"vpl");
1.223     brouard  8289:   /* 1eme*/
1.238     brouard  8290:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8291:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8292:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8293:        k1=TKresult[nres];
1.338     brouard  8294:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8295:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8296:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8297:        /*   continue; */
1.238     brouard  8298:        /* We are interested in selected combination by the resultline */
1.246     brouard  8299:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8300:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8301:        strcpy(gplotlabel,"(");
1.337     brouard  8302:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8303:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8304:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8305: 
                   8306:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8307:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8308:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8309:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8310:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8311:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8312:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8313:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8314:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8315:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8316:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8317:        /* } */
                   8318:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8319:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8320:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8321:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8322:        }
                   8323:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8324:        /* printf("\n#\n"); */
1.238     brouard  8325:        fprintf(ficgp,"\n#\n");
                   8326:        if(invalidvarcomb[k1]){
1.260     brouard  8327:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8328:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8329:          continue;
                   8330:        }
1.235     brouard  8331:       
1.241     brouard  8332:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8333:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8334:        /* 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  8335:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8336:        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);
                   8337:        /* 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); */
                   8338:       /* k1-1 error should be nres-1*/
1.238     brouard  8339:        for (i=1; i<= nlstate ; i ++) {
                   8340:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8341:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8342:        }
1.288     brouard  8343:        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  8344:        for (i=1; i<= nlstate ; i ++) {
                   8345:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8346:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8347:        } 
1.260     brouard  8348:        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  8349:        for (i=1; i<= nlstate ; i ++) {
                   8350:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8351:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8352:        }  
1.265     brouard  8353:        /* 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)); */
                   8354:        
                   8355:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8356:         if(cptcoveff ==0){
1.271     brouard  8357:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8358:        }else{
                   8359:          kl=0;
                   8360:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8361:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8362:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8363:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8364:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8365:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8366:            vlv= nbcode[Tvaraff[k]][lv];
                   8367:            kl++;
                   8368:            /* 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 *\/ */
                   8369:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8370:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8371:            /* ''  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*/
                   8372:            if(k==cptcoveff){
                   8373:              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], \
                   8374:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8375:            }else{
                   8376:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8377:              kl++;
                   8378:            }
                   8379:          } /* end covariate */
                   8380:        } /* end if no covariate */
                   8381: 
1.296     brouard  8382:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8383:          /* 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  8384:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8385:          if(cptcoveff ==0){
1.245     brouard  8386:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8387:          }else{
                   8388:            kl=0;
                   8389:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8390:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8391:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8392:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8393:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8394:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8395:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8396:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8397:              kl++;
1.238     brouard  8398:              /* 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 *\/ */
                   8399:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8400:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8401:              /* ''  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*/
                   8402:              if(k==cptcoveff){
1.245     brouard  8403:                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  8404:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8405:              }else{
1.332     brouard  8406:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8407:                kl++;
                   8408:              }
                   8409:            } /* end covariate */
                   8410:          } /* end if no covariate */
1.296     brouard  8411:          if(prevbcast == 1){
1.268     brouard  8412:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8413:            /* k1-1 error should be nres-1*/
                   8414:            for (i=1; i<= nlstate ; i ++) {
                   8415:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8416:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8417:            }
1.271     brouard  8418:            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  8419:            for (i=1; i<= nlstate ; i ++) {
                   8420:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8421:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8422:            } 
1.276     brouard  8423:            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  8424:            for (i=1; i<= nlstate ; i ++) {
                   8425:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8426:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8427:            } 
1.274     brouard  8428:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8429:          } /* end if backprojcast */
1.296     brouard  8430:        } /* end if prevbcast */
1.276     brouard  8431:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8432:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8433:       } /* nres */
1.337     brouard  8434:     /* } /\* k1 *\/ */
1.201     brouard  8435:   } /* cpt */
1.235     brouard  8436: 
                   8437:   
1.126     brouard  8438:   /*2 eme*/
1.337     brouard  8439:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8440:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8441:       k1=TKresult[nres];
1.338     brouard  8442:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8443:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8444:       /*       continue; */
1.238     brouard  8445:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8446:       strcpy(gplotlabel,"(");
1.337     brouard  8447:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8448:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8449:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8450:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8451:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8452:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8453:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8454:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8455:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8456:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8457:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8458:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8459:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8460:       /* } */
                   8461:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8462:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8463:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8464:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8465:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8466:       }
1.264     brouard  8467:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8468:       fprintf(ficgp,"\n#\n");
1.223     brouard  8469:       if(invalidvarcomb[k1]){
                   8470:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8471:        continue;
                   8472:       }
1.219     brouard  8473:                        
1.241     brouard  8474:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8475:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8476:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8477:        if(vpopbased==0){
1.238     brouard  8478:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8479:        }else
1.238     brouard  8480:          fprintf(ficgp,"\nreplot ");
                   8481:        for (i=1; i<= nlstate+1 ; i ++) {
                   8482:          k=2*i;
1.261     brouard  8483:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased);
1.238     brouard  8484:          for (j=1; j<= nlstate+1 ; j ++) {
                   8485:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8486:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8487:          }   
                   8488:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8489:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8490:          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  8491:          for (j=1; j<= nlstate+1 ; j ++) {
                   8492:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8493:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8494:          }   
                   8495:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8496:          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  8497:          for (j=1; j<= nlstate+1 ; j ++) {
                   8498:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8499:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8500:          }   
                   8501:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8502:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8503:        } /* state */
                   8504:       } /* vpopbased */
1.264     brouard  8505:       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  8506:     } /* end nres */
1.337     brouard  8507:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8508:        
                   8509:        
                   8510:   /*3eme*/
1.337     brouard  8511:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8512:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8513:       k1=TKresult[nres];
1.338     brouard  8514:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8515:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8516:       /*       continue; */
1.238     brouard  8517: 
1.332     brouard  8518:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8519:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8520:        strcpy(gplotlabel,"(");
1.337     brouard  8521:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8522:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8523:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8524:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8525:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8526:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8527:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8528:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8529:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8530:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8531:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8532:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8533:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8534:        /* } */
                   8535:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8536:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8537:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8538:        }
1.264     brouard  8539:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8540:        fprintf(ficgp,"\n#\n");
                   8541:        if(invalidvarcomb[k1]){
                   8542:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8543:          continue;
                   8544:        }
                   8545:                        
                   8546:        /*       k=2+nlstate*(2*cpt-2); */
                   8547:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8548:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8549:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8550:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8551: 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  8552:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8553:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8554:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8555:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8556:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8557:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8558:                                
1.238     brouard  8559:        */
                   8560:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8561:          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  8562:          /*    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  8563:                                
1.238     brouard  8564:        } 
1.261     brouard  8565:        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  8566:       }
1.264     brouard  8567:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8568:     } /* end nres */
1.337     brouard  8569:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8570:   
1.223     brouard  8571:   /* 4eme */
1.201     brouard  8572:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8573:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8574:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8575:       k1=TKresult[nres];
1.338     brouard  8576:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8577:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8578:       /*       continue; */
1.238     brouard  8579:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8580:        strcpy(gplotlabel,"(");
1.337     brouard  8581:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8582:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8583:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8584:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8585:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8586:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8587:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8588:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8589:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8590:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8591:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8592:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8593:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8594:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8595:        /* } */
                   8596:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8597:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8598:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8599:        }       
1.264     brouard  8600:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8601:        fprintf(ficgp,"\n#\n");
                   8602:        if(invalidvarcomb[k1]){
                   8603:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8604:          continue;
1.223     brouard  8605:        }
1.238     brouard  8606:       
1.241     brouard  8607:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8608:        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  8609:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8610: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8611:        k=3;
                   8612:        for (i=1; i<= nlstate ; i ++){
                   8613:          if(i==1){
                   8614:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8615:          }else{
                   8616:            fprintf(ficgp,", '' ");
                   8617:          }
                   8618:          l=(nlstate+ndeath)*(i-1)+1;
                   8619:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8620:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8621:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8622:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8623:        } /* nlstate */
1.264     brouard  8624:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8625:       } /* end cpt state*/ 
                   8626:     } /* end nres */
1.337     brouard  8627:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8628: 
1.220     brouard  8629: /* 5eme */
1.201     brouard  8630:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8631:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8632:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8633:       k1=TKresult[nres];
1.338     brouard  8634:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8635:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8636:       /*       continue; */
1.238     brouard  8637:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8638:        strcpy(gplotlabel,"(");
1.238     brouard  8639:        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  8640:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8641:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8642:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8643:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8644:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8645:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8646:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8647:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8648:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8649:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8650:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8651:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8652:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8653:        /* } */
                   8654:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8655:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8656:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8657:        }       
1.264     brouard  8658:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8659:        fprintf(ficgp,"\n#\n");
                   8660:        if(invalidvarcomb[k1]){
                   8661:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8662:          continue;
                   8663:        }
1.227     brouard  8664:       
1.241     brouard  8665:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8666:        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  8667:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8668: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8669:        k=3;
                   8670:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8671:          if(j==1)
                   8672:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8673:          else
                   8674:            fprintf(ficgp,", '' ");
                   8675:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8676:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8677:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8678:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8679:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8680:        } /* nlstate */
                   8681:        fprintf(ficgp,", '' ");
                   8682:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8683:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8684:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8685:          if(j < nlstate)
                   8686:            fprintf(ficgp,"$%d +",k+l);
                   8687:          else
                   8688:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8689:        }
1.264     brouard  8690:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8691:       } /* end cpt state*/ 
1.337     brouard  8692:     /* } /\* end covariate *\/   */
1.238     brouard  8693:   } /* end nres */
1.227     brouard  8694:   
1.220     brouard  8695: /* 6eme */
1.202     brouard  8696:   /* CV preval stable (period) for each covariate */
1.337     brouard  8697:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8698:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8699:      k1=TKresult[nres];
1.338     brouard  8700:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8701:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8702:      /*  continue; */
1.255     brouard  8703:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8704:       strcpy(gplotlabel,"(");      
1.288     brouard  8705:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8706:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8707:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8708:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8709:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8710:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8711:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8712:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8713:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8714:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8715:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8716:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8717:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8718:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8719:       /* } */
                   8720:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8721:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8722:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8723:       }        
1.264     brouard  8724:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8725:       fprintf(ficgp,"\n#\n");
1.223     brouard  8726:       if(invalidvarcomb[k1]){
1.227     brouard  8727:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8728:        continue;
1.223     brouard  8729:       }
1.227     brouard  8730:       
1.241     brouard  8731:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8732:       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  8733:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8734: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8735:       k=3; /* Offset */
1.255     brouard  8736:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8737:        if(i==1)
                   8738:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8739:        else
                   8740:          fprintf(ficgp,", '' ");
1.255     brouard  8741:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8742:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8743:        for (j=2; j<= nlstate ; j ++)
                   8744:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8745:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8746:       } /* nlstate */
1.264     brouard  8747:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8748:     } /* end cpt state*/ 
                   8749:   } /* end covariate */  
1.227     brouard  8750:   
                   8751:   
1.220     brouard  8752: /* 7eme */
1.296     brouard  8753:   if(prevbcast == 1){
1.288     brouard  8754:     /* CV backward prevalence  for each covariate */
1.337     brouard  8755:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8756:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8757:       k1=TKresult[nres];
1.338     brouard  8758:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8759:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8760:       /*       continue; */
1.268     brouard  8761:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8762:        strcpy(gplotlabel,"(");      
1.288     brouard  8763:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8764:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8765:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8766:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8767:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8768:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8769:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8770:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8771:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8772:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8773:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8774:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8775:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8776:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8777:        /* } */
                   8778:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8779:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8780:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8781:        }       
1.264     brouard  8782:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8783:        fprintf(ficgp,"\n#\n");
                   8784:        if(invalidvarcomb[k1]){
                   8785:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8786:          continue;
                   8787:        }
                   8788:        
1.241     brouard  8789:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8790:        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  8791:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8792: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8793:        k=3; /* Offset */
1.268     brouard  8794:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8795:          if(i==1)
                   8796:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8797:          else
                   8798:            fprintf(ficgp,", '' ");
                   8799:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8800:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8801:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8802:          /* 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  8803:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8804:          /* for (j=2; j<= nlstate ; j ++) */
                   8805:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8806:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8807:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8808:        } /* nlstate */
1.264     brouard  8809:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8810:       } /* end cpt state*/ 
                   8811:     } /* end covariate */  
1.296     brouard  8812:   } /* End if prevbcast */
1.218     brouard  8813:   
1.223     brouard  8814:   /* 8eme */
1.218     brouard  8815:   if(prevfcast==1){
1.288     brouard  8816:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8817:     
1.337     brouard  8818:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8819:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8820:       k1=TKresult[nres];
1.338     brouard  8821:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8822:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8823:       /*       continue; */
1.211     brouard  8824:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8825:        strcpy(gplotlabel,"(");      
1.288     brouard  8826:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8827:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8828:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8829:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8830:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8831:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8832:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8833:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8834:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8835:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8836:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8837:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8838:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8839:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8840:        /* } */
                   8841:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8842:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8843:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8844:        }       
1.264     brouard  8845:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8846:        fprintf(ficgp,"\n#\n");
                   8847:        if(invalidvarcomb[k1]){
                   8848:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8849:          continue;
                   8850:        }
                   8851:        
                   8852:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8853:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8854:        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  8855:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8856: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8857: 
                   8858:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8859:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8860:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8861:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8862:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8863:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8864:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8865:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8866:          if(i==istart){
1.227     brouard  8867:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8868:          }else{
                   8869:            fprintf(ficgp,",\\\n '' ");
                   8870:          }
                   8871:          if(cptcoveff ==0){ /* No covariate */
                   8872:            ioffset=2; /* Age is in 2 */
                   8873:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8874:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8875:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8876:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8877:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8878:            if(i==nlstate+1){
1.270     brouard  8879:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8880:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8881:              fprintf(ficgp,",\\\n '' ");
                   8882:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8883:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8884:                     offyear,                           \
1.268     brouard  8885:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8886:            }else
1.227     brouard  8887:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8888:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8889:          }else{ /* more than 2 covariates */
1.270     brouard  8890:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8891:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8892:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8893:            iyearc=ioffset-1;
                   8894:            iagec=ioffset;
1.227     brouard  8895:            fprintf(ficgp," u %d:(",ioffset); 
                   8896:            kl=0;
                   8897:            strcpy(gplotcondition,"(");
                   8898:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8899:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8900:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8901:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8902:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8903:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8904:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8905:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8906:              kl++;
                   8907:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8908:              kl++;
                   8909:              if(k <cptcoveff && cptcoveff>1)
                   8910:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8911:            }
                   8912:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8913:            /* 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 *\/ */
                   8914:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8915:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8916:            /* ''  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*/
                   8917:            if(i==nlstate+1){
1.270     brouard  8918:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8919:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8920:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8921:              fprintf(ficgp," u %d:(",iagec); 
                   8922:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8923:                      iyearc, iagec, offyear,                           \
                   8924:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8925: /*  '' 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  8926:            }else{
                   8927:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8928:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8929:            }
                   8930:          } /* end if covariate */
                   8931:        } /* nlstate */
1.264     brouard  8932:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8933:       } /* end cpt state*/
                   8934:     } /* end covariate */
                   8935:   } /* End if prevfcast */
1.227     brouard  8936:   
1.296     brouard  8937:   if(prevbcast==1){
1.268     brouard  8938:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8939:     
1.337     brouard  8940:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8941:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8942:      k1=TKresult[nres];
1.338     brouard  8943:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8944:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8945:        /*      continue; */
1.268     brouard  8946:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8947:        strcpy(gplotlabel,"(");      
                   8948:        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  8949:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8950:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8951:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8952:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8953:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8954:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8955:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8956:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8957:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8958:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8959:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8960:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8961:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8962:        /* } */
                   8963:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8964:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8965:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8966:        }       
                   8967:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8968:        fprintf(ficgp,"\n#\n");
                   8969:        if(invalidvarcomb[k1]){
                   8970:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8971:          continue;
                   8972:        }
                   8973:        
                   8974:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8975:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8976:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8977:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8978: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8979: 
                   8980:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8981:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8982:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8983:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8984:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8985:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8986:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8987:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8988:          if(i==istart){
                   8989:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8990:          }else{
                   8991:            fprintf(ficgp,",\\\n '' ");
                   8992:          }
                   8993:          if(cptcoveff ==0){ /* No covariate */
                   8994:            ioffset=2; /* Age is in 2 */
                   8995:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8996:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8997:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8998:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8999:            fprintf(ficgp," u %d:(", ioffset); 
                   9000:            if(i==nlstate+1){
1.270     brouard  9001:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9002:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9003:              fprintf(ficgp,",\\\n '' ");
                   9004:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9005:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9006:                     offbyear,                          \
                   9007:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9008:            }else
                   9009:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9010:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9011:          }else{ /* more than 2 covariates */
1.270     brouard  9012:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9013:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9014:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9015:            iyearc=ioffset-1;
                   9016:            iagec=ioffset;
1.268     brouard  9017:            fprintf(ficgp," u %d:(",ioffset); 
                   9018:            kl=0;
                   9019:            strcpy(gplotcondition,"(");
1.337     brouard  9020:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9021:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9022:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9023:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9024:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9025:                lv=Tvresult[nres][k];
                   9026:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9027:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9028:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9029:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9030:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9031:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9032:                kl++;
                   9033:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9034:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9035:                kl++;
1.338     brouard  9036:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9037:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9038:              }
1.268     brouard  9039:            }
                   9040:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9041:            /* 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 *\/ */
                   9042:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9043:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9044:            /* ''  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*/
                   9045:            if(i==nlstate+1){
1.270     brouard  9046:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9047:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9048:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9049:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9050:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9051:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9052:                      iyearc,iagec,offbyear,                            \
                   9053:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9054: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9055:            }else{
                   9056:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9057:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9058:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9059:            }
                   9060:          } /* end if covariate */
                   9061:        } /* nlstate */
                   9062:        fprintf(ficgp,"\nset out; unset label;\n");
                   9063:       } /* end cpt state*/
                   9064:     } /* end covariate */
1.296     brouard  9065:   } /* End if prevbcast */
1.268     brouard  9066:   
1.227     brouard  9067:   
1.238     brouard  9068:   /* 9eme writing MLE parameters */
                   9069:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9070:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9071:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9072:     for(k=1; k <=(nlstate+ndeath); k++){
                   9073:       if (k != i) {
1.227     brouard  9074:        fprintf(ficgp,"#   current state %d\n",k);
                   9075:        for(j=1; j <=ncovmodel; j++){
                   9076:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9077:          jk++; 
                   9078:        }
                   9079:        fprintf(ficgp,"\n");
1.126     brouard  9080:       }
                   9081:     }
1.223     brouard  9082:   }
1.187     brouard  9083:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9084:   
1.145     brouard  9085:   /*goto avoid;*/
1.238     brouard  9086:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9087:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9088:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9089:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9090:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9091:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9092:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9093:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9094:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9095:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9096:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9097:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9098:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9099:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9100:   fprintf(ficgp,"#\n");
1.223     brouard  9101:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9102:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9103:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9104:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9105:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9106:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9107:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9108:      /* k1=nres; */
1.338     brouard  9109:       k1=TKresult[nres];
                   9110:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9111:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9112:       strcpy(gplotlabel,"(");
1.276     brouard  9113:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9114:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9115:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9116:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9117:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9118:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9119:       }
                   9120:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9121:       /*       continue; */
                   9122:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9123:       /* strcpy(gplotlabel,"("); */
                   9124:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9125:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9126:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9127:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9128:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9129:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9130:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9131:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9132:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9133:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9134:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9135:       /* } */
                   9136:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9137:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9138:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9139:       /* }      */
1.264     brouard  9140:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9141:       fprintf(ficgp,"\n#\n");
1.264     brouard  9142:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9143:       fprintf(ficgp,"\nset key outside ");
                   9144:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9145:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9146:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9147:       if (ng==1){
                   9148:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9149:        fprintf(ficgp,"\nunset log y");
                   9150:       }else if (ng==2){
                   9151:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9152:        fprintf(ficgp,"\nset log y");
                   9153:       }else if (ng==3){
                   9154:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9155:        fprintf(ficgp,"\nset log y");
                   9156:       }else
                   9157:        fprintf(ficgp,"\nunset title ");
                   9158:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9159:       i=1;
                   9160:       for(k2=1; k2<=nlstate; k2++) {
                   9161:        k3=i;
                   9162:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9163:          if (k != k2){
                   9164:            switch( ng) {
                   9165:            case 1:
                   9166:              if(nagesqr==0)
                   9167:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9168:              else /* nagesqr =1 */
                   9169:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9170:              break;
                   9171:            case 2: /* ng=2 */
                   9172:              if(nagesqr==0)
                   9173:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9174:              else /* nagesqr =1 */
                   9175:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9176:              break;
                   9177:            case 3:
                   9178:              if(nagesqr==0)
                   9179:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9180:              else /* nagesqr =1 */
                   9181:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9182:              break;
                   9183:            }
                   9184:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9185:            ijp=1; /* product no age */
                   9186:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9187:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9188:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9189:              switch(Typevar[j]){
                   9190:              case 1:
                   9191:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9192:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9193:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9194:                      if(DummyV[j]==0){/* Bug valgrind */
                   9195:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9196:                      }else{ /* quantitative */
                   9197:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9198:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9199:                      }
                   9200:                      ij++;
1.268     brouard  9201:                    }
1.237     brouard  9202:                  }
1.329     brouard  9203:                }
                   9204:                break;
                   9205:              case 2:
                   9206:                if(cptcovprod >0){
                   9207:                  if(j==Tprod[ijp]) { /* */ 
                   9208:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9209:                    if(ijp <=cptcovprod) { /* Product */
                   9210:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9211:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9212:                          /* 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)]); */
                   9213:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9214:                        }else{ /* Vn is dummy and Vm is quanti */
                   9215:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9216:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9217:                        }
                   9218:                      }else{ /* Vn*Vm Vn is quanti */
                   9219:                        if(DummyV[Tvard[ijp][2]]==0){
                   9220:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9221:                        }else{ /* Both quanti */
                   9222:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9223:                        }
1.268     brouard  9224:                      }
1.329     brouard  9225:                      ijp++;
1.237     brouard  9226:                    }
1.329     brouard  9227:                  } /* end Tprod */
                   9228:                }
                   9229:                break;
                   9230:              case 0:
                   9231:                /* simple covariate */
1.264     brouard  9232:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9233:                if(Dummy[j]==0){
                   9234:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9235:                }else{ /* quantitative */
                   9236:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9237:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9238:                }
1.329     brouard  9239:               /* end simple */
                   9240:                break;
                   9241:              default:
                   9242:                break;
                   9243:              } /* end switch */
1.237     brouard  9244:            } /* end j */
1.329     brouard  9245:          }else{ /* k=k2 */
                   9246:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9247:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9248:            }else
                   9249:              i=i-ncovmodel;
1.223     brouard  9250:          }
1.227     brouard  9251:          
1.223     brouard  9252:          if(ng != 1){
                   9253:            fprintf(ficgp,")/(1");
1.227     brouard  9254:            
1.264     brouard  9255:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9256:              if(nagesqr==0)
1.264     brouard  9257:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9258:              else /* nagesqr =1 */
1.264     brouard  9259:                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  9260:               
1.223     brouard  9261:              ij=1;
1.329     brouard  9262:              ijp=1;
                   9263:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9264:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9265:                switch(Typevar[j]){
                   9266:                case 1:
                   9267:                  if(cptcovage >0){ 
                   9268:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9269:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9270:                        if(DummyV[j]==0){/* Bug valgrind */
                   9271:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9272:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9273:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9274:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9275:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9276:                        }else{ /* quantitative */
                   9277:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9278:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9279:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9280:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9281:                        }
                   9282:                        ij++;
                   9283:                      }
                   9284:                    }
                   9285:                  }
                   9286:                  break;
                   9287:                case 2:
                   9288:                  if(cptcovprod >0){
                   9289:                    if(j==Tprod[ijp]) { /* */ 
                   9290:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9291:                      if(ijp <=cptcovprod) { /* Product */
                   9292:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9293:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9294:                            /* 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)]); */
                   9295:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9296:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9297:                          }else{ /* Vn is dummy and Vm is quanti */
                   9298:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9299:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9300:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9301:                          }
                   9302:                        }else{ /* Vn*Vm Vn is quanti */
                   9303:                          if(DummyV[Tvard[ijp][2]]==0){
                   9304:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9305:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9306:                          }else{ /* Both quanti */
                   9307:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9308:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9309:                          } 
                   9310:                        }
                   9311:                        ijp++;
                   9312:                      }
                   9313:                    } /* end Tprod */
                   9314:                  } /* end if */
                   9315:                  break;
                   9316:                case 0: 
                   9317:                  /* simple covariate */
                   9318:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9319:                  if(Dummy[j]==0){
                   9320:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9321:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9322:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9323:                  }else{ /* quantitative */
                   9324:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9325:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9326:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9327:                  }
                   9328:                  /* end simple */
                   9329:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9330:                  break;
                   9331:                default:
                   9332:                  break;
                   9333:                } /* end switch */
1.223     brouard  9334:              }
                   9335:              fprintf(ficgp,")");
                   9336:            }
                   9337:            fprintf(ficgp,")");
                   9338:            if(ng ==2)
1.276     brouard  9339:              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  9340:            else /* ng= 3 */
1.276     brouard  9341:              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  9342:           }else{ /* end ng <> 1 */
1.223     brouard  9343:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9344:              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  9345:          }
                   9346:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9347:            fprintf(ficgp,",");
                   9348:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9349:            fprintf(ficgp,",");
                   9350:          i=i+ncovmodel;
                   9351:        } /* end k */
                   9352:       } /* end k2 */
1.276     brouard  9353:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9354:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9355:     } /* end resultline */
1.223     brouard  9356:   } /* end ng */
                   9357:   /* avoid: */
                   9358:   fflush(ficgp); 
1.126     brouard  9359: }  /* end gnuplot */
                   9360: 
                   9361: 
                   9362: /*************** Moving average **************/
1.219     brouard  9363: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9364:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9365:    
1.222     brouard  9366:    int i, cpt, cptcod;
                   9367:    int modcovmax =1;
                   9368:    int mobilavrange, mob;
                   9369:    int iage=0;
1.288     brouard  9370:    int firstA1=0, firstA2=0;
1.222     brouard  9371: 
1.266     brouard  9372:    double sum=0., sumr=0.;
1.222     brouard  9373:    double age;
1.266     brouard  9374:    double *sumnewp, *sumnewm, *sumnewmr;
                   9375:    double *agemingood, *agemaxgood; 
                   9376:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9377:   
                   9378:   
1.278     brouard  9379:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9380:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9381: 
                   9382:    sumnewp = vector(1,ncovcombmax);
                   9383:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9384:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9385:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9386:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9387:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9388:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9389: 
                   9390:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9391:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9392:      sumnewp[cptcod]=0.;
1.266     brouard  9393:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9394:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9395:    }
                   9396:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9397:   
1.266     brouard  9398:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9399:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9400:      else mobilavrange=mobilav;
                   9401:      for (age=bage; age<=fage; age++)
                   9402:        for (i=1; i<=nlstate;i++)
                   9403:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9404:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9405:      /* We keep the original values on the extreme ages bage, fage and for 
                   9406:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9407:        we use a 5 terms etc. until the borders are no more concerned. 
                   9408:      */ 
                   9409:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9410:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9411:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9412:           sumnewm[cptcod]=0.;
                   9413:           for (i=1; i<=nlstate;i++){
1.222     brouard  9414:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9415:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9416:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9417:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9418:             }
                   9419:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9420:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9421:           } /* end i */
                   9422:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9423:         } /* end cptcod */
1.222     brouard  9424:        }/* end age */
                   9425:      }/* end mob */
1.266     brouard  9426:    }else{
                   9427:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9428:      return -1;
1.266     brouard  9429:    }
                   9430: 
                   9431:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9432:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9433:      if(invalidvarcomb[cptcod]){
                   9434:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9435:        continue;
                   9436:      }
1.219     brouard  9437: 
1.266     brouard  9438:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9439:        sumnewm[cptcod]=0.;
                   9440:        sumnewmr[cptcod]=0.;
                   9441:        for (i=1; i<=nlstate;i++){
                   9442:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9443:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9444:        }
                   9445:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9446:         agemingoodr[cptcod]=age;
                   9447:        }
                   9448:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9449:           agemingood[cptcod]=age;
                   9450:        }
                   9451:      } /* age */
                   9452:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9453:        sumnewm[cptcod]=0.;
1.266     brouard  9454:        sumnewmr[cptcod]=0.;
1.222     brouard  9455:        for (i=1; i<=nlstate;i++){
                   9456:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9457:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9458:        }
                   9459:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9460:         agemaxgoodr[cptcod]=age;
1.222     brouard  9461:        }
                   9462:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9463:         agemaxgood[cptcod]=age;
                   9464:        }
                   9465:      } /* age */
                   9466:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9467:      /* but they will change */
1.288     brouard  9468:      firstA1=0;firstA2=0;
1.266     brouard  9469:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9470:        sumnewm[cptcod]=0.;
                   9471:        sumnewmr[cptcod]=0.;
                   9472:        for (i=1; i<=nlstate;i++){
                   9473:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9474:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9475:        }
                   9476:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9477:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9478:           agemaxgoodr[cptcod]=age;  /* age min */
                   9479:           for (i=1; i<=nlstate;i++)
                   9480:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9481:         }else{ /* bad we change the value with the values of good ages */
                   9482:           for (i=1; i<=nlstate;i++){
                   9483:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9484:           } /* i */
                   9485:         } /* end bad */
                   9486:        }else{
                   9487:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9488:           agemaxgood[cptcod]=age;
                   9489:         }else{ /* bad we change the value with the values of good ages */
                   9490:           for (i=1; i<=nlstate;i++){
                   9491:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9492:           } /* i */
                   9493:         } /* end bad */
                   9494:        }/* end else */
                   9495:        sum=0.;sumr=0.;
                   9496:        for (i=1; i<=nlstate;i++){
                   9497:         sum+=mobaverage[(int)age][i][cptcod];
                   9498:         sumr+=probs[(int)age][i][cptcod];
                   9499:        }
                   9500:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9501:         if(!firstA1){
                   9502:           firstA1=1;
                   9503:           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);
                   9504:         }
                   9505:         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  9506:        } /* end bad */
                   9507:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9508:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9509:         if(!firstA2){
                   9510:           firstA2=1;
                   9511:           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);
                   9512:         }
                   9513:         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  9514:        } /* end bad */
                   9515:      }/* age */
1.266     brouard  9516: 
                   9517:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9518:        sumnewm[cptcod]=0.;
1.266     brouard  9519:        sumnewmr[cptcod]=0.;
1.222     brouard  9520:        for (i=1; i<=nlstate;i++){
                   9521:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9522:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9523:        } 
                   9524:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9525:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9526:           agemingoodr[cptcod]=age;
                   9527:           for (i=1; i<=nlstate;i++)
                   9528:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9529:         }else{ /* bad we change the value with the values of good ages */
                   9530:           for (i=1; i<=nlstate;i++){
                   9531:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9532:           } /* i */
                   9533:         } /* end bad */
                   9534:        }else{
                   9535:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9536:           agemingood[cptcod]=age;
                   9537:         }else{ /* bad */
                   9538:           for (i=1; i<=nlstate;i++){
                   9539:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9540:           } /* i */
                   9541:         } /* end bad */
                   9542:        }/* end else */
                   9543:        sum=0.;sumr=0.;
                   9544:        for (i=1; i<=nlstate;i++){
                   9545:         sum+=mobaverage[(int)age][i][cptcod];
                   9546:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9547:        }
1.266     brouard  9548:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9549:         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  9550:        } /* end bad */
                   9551:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9552:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9553:         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  9554:        } /* end bad */
                   9555:      }/* age */
1.266     brouard  9556: 
1.222     brouard  9557:                
                   9558:      for (age=bage; age<=fage; age++){
1.235     brouard  9559:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9560:        sumnewp[cptcod]=0.;
                   9561:        sumnewm[cptcod]=0.;
                   9562:        for (i=1; i<=nlstate;i++){
                   9563:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9564:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9565:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9566:        }
                   9567:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9568:      }
                   9569:      /* printf("\n"); */
                   9570:      /* } */
1.266     brouard  9571: 
1.222     brouard  9572:      /* brutal averaging */
1.266     brouard  9573:      /* for (i=1; i<=nlstate;i++){ */
                   9574:      /*   for (age=1; age<=bage; age++){ */
                   9575:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9576:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9577:      /*   }     */
                   9578:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9579:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9580:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9581:      /*   } */
                   9582:      /* } /\* end i status *\/ */
                   9583:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9584:      /*   for (age=1; age<=AGESUP; age++){ */
                   9585:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9586:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9587:      /*   } */
                   9588:      /* } */
1.222     brouard  9589:    }/* end cptcod */
1.266     brouard  9590:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9591:    free_vector(agemaxgood,1, ncovcombmax);
                   9592:    free_vector(agemingood,1, ncovcombmax);
                   9593:    free_vector(agemingoodr,1, ncovcombmax);
                   9594:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9595:    free_vector(sumnewm,1, ncovcombmax);
                   9596:    free_vector(sumnewp,1, ncovcombmax);
                   9597:    return 0;
                   9598:  }/* End movingaverage */
1.218     brouard  9599:  
1.126     brouard  9600: 
1.296     brouard  9601:  
1.126     brouard  9602: /************** Forecasting ******************/
1.296     brouard  9603: /* 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)*/
                   9604: 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){
                   9605:   /* dateintemean, mean date of interviews
                   9606:      dateprojd, year, month, day of starting projection 
                   9607:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9608:      agemin, agemax range of age
                   9609:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9610:   */
1.296     brouard  9611:   /* double anprojd, mprojd, jprojd; */
                   9612:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9613:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9614:   double agec; /* generic age */
1.296     brouard  9615:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9616:   double *popeffectif,*popcount;
                   9617:   double ***p3mat;
1.218     brouard  9618:   /* double ***mobaverage; */
1.126     brouard  9619:   char fileresf[FILENAMELENGTH];
                   9620: 
                   9621:   agelim=AGESUP;
1.211     brouard  9622:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9623:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9624:      We still use firstpass and lastpass as another selection.
                   9625:   */
1.214     brouard  9626:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9627:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9628:  
1.201     brouard  9629:   strcpy(fileresf,"F_"); 
                   9630:   strcat(fileresf,fileresu);
1.126     brouard  9631:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9632:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9633:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9634:   }
1.235     brouard  9635:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9636:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9637: 
1.225     brouard  9638:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9639: 
                   9640: 
                   9641:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9642:   if (stepm<=12) stepsize=1;
                   9643:   if(estepm < stepm){
                   9644:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9645:   }
1.270     brouard  9646:   else{
                   9647:     hstepm=estepm;   
                   9648:   }
                   9649:   if(estepm > stepm){ /* Yes every two year */
                   9650:     stepsize=2;
                   9651:   }
1.296     brouard  9652:   hstepm=hstepm/stepm;
1.126     brouard  9653: 
1.296     brouard  9654:   
                   9655:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9656:   /*                              fractional in yp1 *\/ */
                   9657:   /* aintmean=yp; */
                   9658:   /* yp2=modf((yp1*12),&yp); */
                   9659:   /* mintmean=yp; */
                   9660:   /* yp1=modf((yp2*30.5),&yp); */
                   9661:   /* jintmean=yp; */
                   9662:   /* if(jintmean==0) jintmean=1; */
                   9663:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9664: 
1.296     brouard  9665: 
                   9666:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9667:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9668:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9669:   i1=pow(2,cptcoveff);
1.126     brouard  9670:   if (cptcovn < 1){i1=1;}
                   9671:   
1.296     brouard  9672:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9673:   
                   9674:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9675:   
1.126     brouard  9676: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9677:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9678:     for(k=1; k<=i1;k++){ /* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) */
1.253     brouard  9679:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9680:       continue;
1.227     brouard  9681:     if(invalidvarcomb[k]){
                   9682:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9683:       continue;
                   9684:     }
                   9685:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9686:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9687:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9688:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9689:     }
1.235     brouard  9690:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9691:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9692:     }
1.227     brouard  9693:     fprintf(ficresf," yearproj age");
                   9694:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9695:       for(i=1; i<=nlstate;i++)               
                   9696:        fprintf(ficresf," p%d%d",i,j);
                   9697:       fprintf(ficresf," wp.%d",j);
                   9698:     }
1.296     brouard  9699:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9700:       fprintf(ficresf,"\n");
1.296     brouard  9701:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9702:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9703:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9704:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9705:        nhstepm = nhstepm/hstepm; 
                   9706:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9707:        oldm=oldms;savm=savms;
1.268     brouard  9708:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9709:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9710:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9711:        for (h=0; h<=nhstepm; h++){
                   9712:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9713:            break;
                   9714:          }
                   9715:        }
                   9716:        fprintf(ficresf,"\n");
                   9717:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9718:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9719:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9720:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9721:        
                   9722:        for(j=1; j<=nlstate+ndeath;j++) {
                   9723:          ppij=0.;
                   9724:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9725:            if (mobilav>=1)
                   9726:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9727:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9728:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9729:            }
1.268     brouard  9730:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9731:          } /* end i */
                   9732:          fprintf(ficresf," %.3f", ppij);
                   9733:        }/* end j */
1.227     brouard  9734:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9735:       } /* end agec */
1.266     brouard  9736:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9737:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9738:     } /* end yearp */
                   9739:   } /* end  k */
1.219     brouard  9740:        
1.126     brouard  9741:   fclose(ficresf);
1.215     brouard  9742:   printf("End of Computing forecasting \n");
                   9743:   fprintf(ficlog,"End of Computing forecasting\n");
                   9744: 
1.126     brouard  9745: }
                   9746: 
1.269     brouard  9747: /************** Back Forecasting ******************/
1.296     brouard  9748:  /* 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){ */
                   9749:  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){
                   9750:   /* back1, year, month, day of starting backprojection
1.267     brouard  9751:      agemin, agemax range of age
                   9752:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9753:      anback2 year of end of backprojection (same day and month as back1).
                   9754:      prevacurrent and prev are prevalences.
1.267     brouard  9755:   */
                   9756:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9757:   double agec; /* generic age */
1.302     brouard  9758:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9759:   double *popeffectif,*popcount;
                   9760:   double ***p3mat;
                   9761:   /* double ***mobaverage; */
                   9762:   char fileresfb[FILENAMELENGTH];
                   9763:  
1.268     brouard  9764:   agelim=AGEINF;
1.267     brouard  9765:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9766:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9767:      We still use firstpass and lastpass as another selection.
                   9768:   */
                   9769:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9770:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9771: 
                   9772:   /*Do we need to compute prevalence again?*/
                   9773: 
                   9774:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9775:   
                   9776:   strcpy(fileresfb,"FB_");
                   9777:   strcat(fileresfb,fileresu);
                   9778:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9779:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9780:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9781:   }
                   9782:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9783:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9784:   
                   9785:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9786:   
                   9787:    
                   9788:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9789:   if (stepm<=12) stepsize=1;
                   9790:   if(estepm < stepm){
                   9791:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9792:   }
1.270     brouard  9793:   else{
                   9794:     hstepm=estepm;   
                   9795:   }
                   9796:   if(estepm >= stepm){ /* Yes every two year */
                   9797:     stepsize=2;
                   9798:   }
1.267     brouard  9799:   
                   9800:   hstepm=hstepm/stepm;
1.296     brouard  9801:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9802:   /*                              fractional in yp1 *\/ */
                   9803:   /* aintmean=yp; */
                   9804:   /* yp2=modf((yp1*12),&yp); */
                   9805:   /* mintmean=yp; */
                   9806:   /* yp1=modf((yp2*30.5),&yp); */
                   9807:   /* jintmean=yp; */
                   9808:   /* if(jintmean==0) jintmean=1; */
                   9809:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9810:   
                   9811:   i1=pow(2,cptcoveff);
                   9812:   if (cptcovn < 1){i1=1;}
                   9813:   
1.296     brouard  9814:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9815:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9816:   
                   9817:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9818:   
                   9819:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9820:   for(k=1; k<=i1;k++){
                   9821:     if(i1 != 1 && TKresult[nres]!= k)
                   9822:       continue;
                   9823:     if(invalidvarcomb[k]){
                   9824:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9825:       continue;
                   9826:     }
1.268     brouard  9827:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9828:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9829:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9830:     }
                   9831:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9832:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9833:     }
                   9834:     fprintf(ficresfb," yearbproj age");
                   9835:     for(j=1; j<=nlstate+ndeath;j++){
                   9836:       for(i=1; i<=nlstate;i++)
1.268     brouard  9837:        fprintf(ficresfb," b%d%d",i,j);
                   9838:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9839:     }
1.296     brouard  9840:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9841:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9842:       fprintf(ficresfb,"\n");
1.296     brouard  9843:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9844:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9845:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9846:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9847:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9848:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9849:        nhstepm = nhstepm/hstepm;
                   9850:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9851:        oldm=oldms;savm=savms;
1.268     brouard  9852:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9853:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9854:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9855:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9856:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9857:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9858:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9859:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9860:            break;
                   9861:          }
                   9862:        }
                   9863:        fprintf(ficresfb,"\n");
                   9864:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9865:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9866:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9867:        for(i=1; i<=nlstate+ndeath;i++) {
                   9868:          ppij=0.;ppi=0.;
                   9869:          for(j=1; j<=nlstate;j++) {
                   9870:            /* if (mobilav==1) */
1.269     brouard  9871:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9872:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9873:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9874:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9875:              /* else { */
                   9876:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9877:              /* } */
1.268     brouard  9878:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9879:          } /* end j */
                   9880:          if(ppi <0.99){
                   9881:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9882:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9883:          }
                   9884:          fprintf(ficresfb," %.3f", ppij);
                   9885:        }/* end j */
1.267     brouard  9886:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9887:       } /* end agec */
                   9888:     } /* end yearp */
                   9889:   } /* end k */
1.217     brouard  9890:   
1.267     brouard  9891:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9892:   
1.267     brouard  9893:   fclose(ficresfb);
                   9894:   printf("End of Computing Back forecasting \n");
                   9895:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9896:        
1.267     brouard  9897: }
1.217     brouard  9898: 
1.269     brouard  9899: /* Variance of prevalence limit: varprlim */
                   9900:  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  9901:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9902:  
                   9903:    char fileresvpl[FILENAMELENGTH];  
                   9904:    FILE *ficresvpl;
                   9905:    double **oldm, **savm;
                   9906:    double **varpl; /* Variances of prevalence limits by age */   
                   9907:    int i1, k, nres, j ;
                   9908:    
                   9909:     strcpy(fileresvpl,"VPL_");
                   9910:     strcat(fileresvpl,fileresu);
                   9911:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9912:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9913:       exit(0);
                   9914:     }
1.288     brouard  9915:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9916:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9917:     
                   9918:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9919:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9920:     
                   9921:     i1=pow(2,cptcoveff);
                   9922:     if (cptcovn < 1){i1=1;}
                   9923: 
1.337     brouard  9924:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9925:        k=TKresult[nres];
1.338     brouard  9926:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9927:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9928:       if(i1 != 1 && TKresult[nres]!= k)
                   9929:        continue;
                   9930:       fprintf(ficresvpl,"\n#****** ");
                   9931:       printf("\n#****** ");
                   9932:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9933:       for(j=1;j<=cptcovs;j++) {
                   9934:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9935:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9936:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9937:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9938:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9939:       }
1.337     brouard  9940:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9941:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9942:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9943:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9944:       /* }      */
1.269     brouard  9945:       fprintf(ficresvpl,"******\n");
                   9946:       printf("******\n");
                   9947:       fprintf(ficlog,"******\n");
                   9948:       
                   9949:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9950:       oldm=oldms;savm=savms;
                   9951:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9952:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9953:       /*}*/
                   9954:     }
                   9955:     
                   9956:     fclose(ficresvpl);
1.288     brouard  9957:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9958:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9959: 
                   9960:  }
                   9961: /* Variance of back prevalence: varbprlim */
                   9962:  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){
                   9963:       /*------- Variance of back (stable) prevalence------*/
                   9964: 
                   9965:    char fileresvbl[FILENAMELENGTH];  
                   9966:    FILE  *ficresvbl;
                   9967: 
                   9968:    double **oldm, **savm;
                   9969:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9970:    int i1, k, nres, j ;
                   9971: 
                   9972:    strcpy(fileresvbl,"VBL_");
                   9973:    strcat(fileresvbl,fileresu);
                   9974:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9975:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9976:      exit(0);
                   9977:    }
                   9978:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9979:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9980:    
                   9981:    
                   9982:    i1=pow(2,cptcoveff);
                   9983:    if (cptcovn < 1){i1=1;}
                   9984:    
1.337     brouard  9985:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9986:      k=TKresult[nres];
1.338     brouard  9987:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9988:     /* for(k=1; k<=i1;k++){ */
                   9989:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9990:     /*          continue; */
1.269     brouard  9991:        fprintf(ficresvbl,"\n#****** ");
                   9992:        printf("\n#****** ");
                   9993:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9994:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  9995:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9996:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9997:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  9998:        /* for(j=1;j<=cptcoveff;j++) { */
                   9999:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10000:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10001:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10002:        /* } */
                   10003:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10004:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10005:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10006:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10007:        }
                   10008:        fprintf(ficresvbl,"******\n");
                   10009:        printf("******\n");
                   10010:        fprintf(ficlog,"******\n");
                   10011:        
                   10012:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10013:        oldm=oldms;savm=savms;
                   10014:        
                   10015:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10016:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10017:        /*}*/
                   10018:      }
                   10019:    
                   10020:    fclose(ficresvbl);
                   10021:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10022:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10023: 
                   10024:  } /* End of varbprlim */
                   10025: 
1.126     brouard  10026: /************** Forecasting *****not tested NB*************/
1.227     brouard  10027: /* 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  10028:   
1.227     brouard  10029: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10030: /*   int *popage; */
                   10031: /*   double calagedatem, agelim, kk1, kk2; */
                   10032: /*   double *popeffectif,*popcount; */
                   10033: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10034: /*   /\* double ***mobaverage; *\/ */
                   10035: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10036: 
1.227     brouard  10037: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10038: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10039: /*   agelim=AGESUP; */
                   10040: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10041:   
1.227     brouard  10042: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10043:   
                   10044:   
1.227     brouard  10045: /*   strcpy(filerespop,"POP_");  */
                   10046: /*   strcat(filerespop,fileresu); */
                   10047: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10048: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10049: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10050: /*   } */
                   10051: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10052: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10053: 
1.227     brouard  10054: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10055: 
1.227     brouard  10056: /*   /\* if (mobilav!=0) { *\/ */
                   10057: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10058: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10059: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10060: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10061: /*   /\*   } *\/ */
                   10062: /*   /\* } *\/ */
1.126     brouard  10063: 
1.227     brouard  10064: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10065: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10066:   
1.227     brouard  10067: /*   agelim=AGESUP; */
1.126     brouard  10068:   
1.227     brouard  10069: /*   hstepm=1; */
                   10070: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10071:        
1.227     brouard  10072: /*   if (popforecast==1) { */
                   10073: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10074: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10075: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10076: /*     }  */
                   10077: /*     popage=ivector(0,AGESUP); */
                   10078: /*     popeffectif=vector(0,AGESUP); */
                   10079: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10080:     
1.227     brouard  10081: /*     i=1;    */
                   10082: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10083:     
1.227     brouard  10084: /*     imx=i; */
                   10085: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10086: /*   } */
1.218     brouard  10087:   
1.227     brouard  10088: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10089: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10090: /*       k=k+1; */
                   10091: /*       fprintf(ficrespop,"\n#******"); */
                   10092: /*       for(j=1;j<=cptcoveff;j++) { */
                   10093: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10094: /*       } */
                   10095: /*       fprintf(ficrespop,"******\n"); */
                   10096: /*       fprintf(ficrespop,"# Age"); */
                   10097: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10098: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10099:       
1.227     brouard  10100: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10101: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10102:        
1.227     brouard  10103: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10104: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10105: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10106:          
1.227     brouard  10107: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10108: /*       oldm=oldms;savm=savms; */
                   10109: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10110:          
1.227     brouard  10111: /*       for (h=0; h<=nhstepm; h++){ */
                   10112: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10113: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10114: /*         }  */
                   10115: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10116: /*           kk1=0.;kk2=0; */
                   10117: /*           for(i=1; i<=nlstate;i++) {               */
                   10118: /*             if (mobilav==1)  */
                   10119: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10120: /*             else { */
                   10121: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10122: /*             } */
                   10123: /*           } */
                   10124: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10125: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10126: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10127: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10128: /*           } */
                   10129: /*         } */
                   10130: /*         for(i=1; i<=nlstate;i++){ */
                   10131: /*           kk1=0.; */
                   10132: /*           for(j=1; j<=nlstate;j++){ */
                   10133: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10134: /*           } */
                   10135: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10136: /*         } */
1.218     brouard  10137:            
1.227     brouard  10138: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10139: /*           for(j=1; j<=nlstate;j++)  */
                   10140: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10141: /*       } */
                   10142: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10143: /*     } */
                   10144: /*       } */
1.218     brouard  10145:       
1.227     brouard  10146: /*       /\******\/ */
1.218     brouard  10147:       
1.227     brouard  10148: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10149: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10150: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10151: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10152: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10153:          
1.227     brouard  10154: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10155: /*       oldm=oldms;savm=savms; */
                   10156: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10157: /*       for (h=0; h<=nhstepm; h++){ */
                   10158: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10159: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10160: /*         }  */
                   10161: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10162: /*           kk1=0.;kk2=0; */
                   10163: /*           for(i=1; i<=nlstate;i++) {               */
                   10164: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10165: /*           } */
                   10166: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10167: /*         } */
                   10168: /*       } */
                   10169: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10170: /*     } */
                   10171: /*       } */
                   10172: /*     }  */
                   10173: /*   } */
1.218     brouard  10174:   
1.227     brouard  10175: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10176:   
1.227     brouard  10177: /*   if (popforecast==1) { */
                   10178: /*     free_ivector(popage,0,AGESUP); */
                   10179: /*     free_vector(popeffectif,0,AGESUP); */
                   10180: /*     free_vector(popcount,0,AGESUP); */
                   10181: /*   } */
                   10182: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10183: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10184: /*   fclose(ficrespop); */
                   10185: /* } /\* End of popforecast *\/ */
1.218     brouard  10186:  
1.126     brouard  10187: int fileappend(FILE *fichier, char *optionfich)
                   10188: {
                   10189:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10190:     printf("Problem with file: %s\n", optionfich);
                   10191:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10192:     return (0);
                   10193:   }
                   10194:   fflush(fichier);
                   10195:   return (1);
                   10196: }
                   10197: 
                   10198: 
                   10199: /**************** function prwizard **********************/
                   10200: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10201: {
                   10202: 
                   10203:   /* Wizard to print covariance matrix template */
                   10204: 
1.164     brouard  10205:   char ca[32], cb[32];
                   10206:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10207:   int numlinepar;
                   10208: 
                   10209:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10210:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10211:   for(i=1; i <=nlstate; i++){
                   10212:     jj=0;
                   10213:     for(j=1; j <=nlstate+ndeath; j++){
                   10214:       if(j==i) continue;
                   10215:       jj++;
                   10216:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10217:       printf("%1d%1d",i,j);
                   10218:       fprintf(ficparo,"%1d%1d",i,j);
                   10219:       for(k=1; k<=ncovmodel;k++){
                   10220:        /*        printf(" %lf",param[i][j][k]); */
                   10221:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10222:        printf(" 0.");
                   10223:        fprintf(ficparo," 0.");
                   10224:       }
                   10225:       printf("\n");
                   10226:       fprintf(ficparo,"\n");
                   10227:     }
                   10228:   }
                   10229:   printf("# Scales (for hessian or gradient estimation)\n");
                   10230:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10231:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10232:   for(i=1; i <=nlstate; i++){
                   10233:     jj=0;
                   10234:     for(j=1; j <=nlstate+ndeath; j++){
                   10235:       if(j==i) continue;
                   10236:       jj++;
                   10237:       fprintf(ficparo,"%1d%1d",i,j);
                   10238:       printf("%1d%1d",i,j);
                   10239:       fflush(stdout);
                   10240:       for(k=1; k<=ncovmodel;k++){
                   10241:        /*      printf(" %le",delti3[i][j][k]); */
                   10242:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10243:        printf(" 0.");
                   10244:        fprintf(ficparo," 0.");
                   10245:       }
                   10246:       numlinepar++;
                   10247:       printf("\n");
                   10248:       fprintf(ficparo,"\n");
                   10249:     }
                   10250:   }
                   10251:   printf("# Covariance matrix\n");
                   10252: /* # 121 Var(a12)\n\ */
                   10253: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10254: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10255: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10256: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10257: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10258: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10259: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10260:   fflush(stdout);
                   10261:   fprintf(ficparo,"# Covariance matrix\n");
                   10262:   /* # 121 Var(a12)\n\ */
                   10263:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10264:   /* #   ...\n\ */
                   10265:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10266:   
                   10267:   for(itimes=1;itimes<=2;itimes++){
                   10268:     jj=0;
                   10269:     for(i=1; i <=nlstate; i++){
                   10270:       for(j=1; j <=nlstate+ndeath; j++){
                   10271:        if(j==i) continue;
                   10272:        for(k=1; k<=ncovmodel;k++){
                   10273:          jj++;
                   10274:          ca[0]= k+'a'-1;ca[1]='\0';
                   10275:          if(itimes==1){
                   10276:            printf("#%1d%1d%d",i,j,k);
                   10277:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10278:          }else{
                   10279:            printf("%1d%1d%d",i,j,k);
                   10280:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10281:            /*  printf(" %.5le",matcov[i][j]); */
                   10282:          }
                   10283:          ll=0;
                   10284:          for(li=1;li <=nlstate; li++){
                   10285:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10286:              if(lj==li) continue;
                   10287:              for(lk=1;lk<=ncovmodel;lk++){
                   10288:                ll++;
                   10289:                if(ll<=jj){
                   10290:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10291:                  if(ll<jj){
                   10292:                    if(itimes==1){
                   10293:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10294:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10295:                    }else{
                   10296:                      printf(" 0.");
                   10297:                      fprintf(ficparo," 0.");
                   10298:                    }
                   10299:                  }else{
                   10300:                    if(itimes==1){
                   10301:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10302:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10303:                    }else{
                   10304:                      printf(" 0.");
                   10305:                      fprintf(ficparo," 0.");
                   10306:                    }
                   10307:                  }
                   10308:                }
                   10309:              } /* end lk */
                   10310:            } /* end lj */
                   10311:          } /* end li */
                   10312:          printf("\n");
                   10313:          fprintf(ficparo,"\n");
                   10314:          numlinepar++;
                   10315:        } /* end k*/
                   10316:       } /*end j */
                   10317:     } /* end i */
                   10318:   } /* end itimes */
                   10319: 
                   10320: } /* end of prwizard */
                   10321: /******************* Gompertz Likelihood ******************************/
                   10322: double gompertz(double x[])
                   10323: { 
1.302     brouard  10324:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10325:   int i,n=0; /* n is the size of the sample */
                   10326: 
1.220     brouard  10327:   for (i=1;i<=imx ; i++) {
1.126     brouard  10328:     sump=sump+weight[i];
                   10329:     /*    sump=sump+1;*/
                   10330:     num=num+1;
                   10331:   }
1.302     brouard  10332:   L=0.0;
                   10333:   /* agegomp=AGEGOMP; */
1.126     brouard  10334:   /* for (i=0; i<=imx; i++) 
                   10335:      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]);*/
                   10336: 
1.302     brouard  10337:   for (i=1;i<=imx ; i++) {
                   10338:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10339:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10340:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10341:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10342:      * +
                   10343:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10344:      */
                   10345:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10346:        if (cens[i] == 1){
                   10347:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10348:        } else if (cens[i] == 0){
1.126     brouard  10349:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10350:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10351:       } else
                   10352:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10353:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10354:        L=L+A*weight[i];
1.126     brouard  10355:        /*      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  10356:      }
                   10357:   }
1.126     brouard  10358: 
1.302     brouard  10359:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10360:  
                   10361:   return -2*L*num/sump;
                   10362: }
                   10363: 
1.136     brouard  10364: #ifdef GSL
                   10365: /******************* Gompertz_f Likelihood ******************************/
                   10366: double gompertz_f(const gsl_vector *v, void *params)
                   10367: { 
1.302     brouard  10368:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10369:   double *x= (double *) v->data;
                   10370:   int i,n=0; /* n is the size of the sample */
                   10371: 
                   10372:   for (i=0;i<=imx-1 ; i++) {
                   10373:     sump=sump+weight[i];
                   10374:     /*    sump=sump+1;*/
                   10375:     num=num+1;
                   10376:   }
                   10377:  
                   10378:  
                   10379:   /* for (i=0; i<=imx; i++) 
                   10380:      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]);*/
                   10381:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10382:   for (i=1;i<=imx ; i++)
                   10383:     {
                   10384:       if (cens[i] == 1 && wav[i]>1)
                   10385:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10386:       
                   10387:       if (cens[i] == 0 && wav[i]>1)
                   10388:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10389:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10390:       
                   10391:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10392:       if (wav[i] > 1 ) { /* ??? */
                   10393:        LL=LL+A*weight[i];
                   10394:        /*      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]);*/
                   10395:       }
                   10396:     }
                   10397: 
                   10398:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10399:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10400:  
                   10401:   return -2*LL*num/sump;
                   10402: }
                   10403: #endif
                   10404: 
1.126     brouard  10405: /******************* Printing html file ***********/
1.201     brouard  10406: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10407:                  int lastpass, int stepm, int weightopt, char model[],\
                   10408:                  int imx,  double p[],double **matcov,double agemortsup){
                   10409:   int i,k;
                   10410: 
                   10411:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10412:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10413:   for (i=1;i<=2;i++) 
                   10414:     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  10415:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10416:   fprintf(fichtm,"</ul>");
                   10417: 
                   10418: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10419: 
                   10420:  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>");
                   10421: 
                   10422:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10423:    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]);
                   10424: 
                   10425:  
                   10426:   fflush(fichtm);
                   10427: }
                   10428: 
                   10429: /******************* Gnuplot file **************/
1.201     brouard  10430: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10431: 
                   10432:   char dirfileres[132],optfileres[132];
1.164     brouard  10433: 
1.126     brouard  10434:   int ng;
                   10435: 
                   10436: 
                   10437:   /*#ifdef windows */
                   10438:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10439:     /*#endif */
                   10440: 
                   10441: 
                   10442:   strcpy(dirfileres,optionfilefiname);
                   10443:   strcpy(optfileres,"vpl");
1.199     brouard  10444:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10445:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10446:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10447:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10448:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10449: 
                   10450: } 
                   10451: 
1.136     brouard  10452: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10453: {
1.126     brouard  10454: 
1.136     brouard  10455:   /*-------- data file ----------*/
                   10456:   FILE *fic;
                   10457:   char dummy[]="                         ";
1.240     brouard  10458:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10459:   int lstra;
1.136     brouard  10460:   int linei, month, year,iout;
1.302     brouard  10461:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10462:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10463:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10464:   char *stratrunc;
1.223     brouard  10465: 
1.240     brouard  10466:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10467:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10468:   for(v=1;v<NCOVMAX;v++){
                   10469:     DummyV[v]=0;
                   10470:     FixedV[v]=0;
                   10471:   }
1.126     brouard  10472: 
1.240     brouard  10473:   for(v=1; v <=ncovcol;v++){
                   10474:     DummyV[v]=0;
                   10475:     FixedV[v]=0;
                   10476:   }
                   10477:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10478:     DummyV[v]=1;
                   10479:     FixedV[v]=0;
                   10480:   }
                   10481:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10482:     DummyV[v]=0;
                   10483:     FixedV[v]=1;
                   10484:   }
                   10485:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10486:     DummyV[v]=1;
                   10487:     FixedV[v]=1;
                   10488:   }
                   10489:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10490:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10491:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10492:   }
1.339     brouard  10493:   
                   10494:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10495:   
1.136     brouard  10496:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10497:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10498:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10499:   }
1.126     brouard  10500: 
1.302     brouard  10501:     /* Is it a BOM UTF-8 Windows file? */
                   10502:   /* First data line */
                   10503:   linei=0;
                   10504:   while(fgets(line, MAXLINE, fic)) {
                   10505:     noffset=0;
                   10506:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10507:     {
                   10508:       noffset=noffset+3;
                   10509:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10510:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10511:       fflush(ficlog); return 1;
                   10512:     }
                   10513:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10514:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10515:     {
                   10516:       noffset=noffset+2;
1.304     brouard  10517:       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);
                   10518:       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  10519:       fflush(ficlog); return 1;
                   10520:     }
                   10521:     else if( line[0] == 0 && line[1] == 0)
                   10522:     {
                   10523:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10524:        noffset=noffset+4;
1.304     brouard  10525:        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);
                   10526:        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  10527:        fflush(ficlog); return 1;
                   10528:       }
                   10529:     } else{
                   10530:       ;/*printf(" Not a BOM file\n");*/
                   10531:     }
                   10532:         /* If line starts with a # it is a comment */
                   10533:     if (line[noffset] == '#') {
                   10534:       linei=linei+1;
                   10535:       break;
                   10536:     }else{
                   10537:       break;
                   10538:     }
                   10539:   }
                   10540:   fclose(fic);
                   10541:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10542:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10543:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10544:   }
                   10545:   /* Not a Bom file */
                   10546:   
1.136     brouard  10547:   i=1;
                   10548:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10549:     linei=linei+1;
                   10550:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10551:       if(line[j] == '\t')
                   10552:        line[j] = ' ';
                   10553:     }
                   10554:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10555:       ;
                   10556:     };
                   10557:     line[j+1]=0;  /* Trims blanks at end of line */
                   10558:     if(line[0]=='#'){
                   10559:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10560:       printf("Comment line\n%s\n",line);
                   10561:       continue;
                   10562:     }
                   10563:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10564:     strcpy(line, linetmp);
1.223     brouard  10565:     
                   10566:     /* Loops on waves */
                   10567:     for (j=maxwav;j>=1;j--){
                   10568:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10569:        cutv(stra, strb, line, ' '); 
                   10570:        if(strb[0]=='.') { /* Missing value */
                   10571:          lval=-1;
                   10572:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10573:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10574:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10575:            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);
                   10576:            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);
                   10577:            return 1;
                   10578:          }
                   10579:        }else{
                   10580:          errno=0;
                   10581:          /* what_kind_of_number(strb); */
                   10582:          dval=strtod(strb,&endptr); 
                   10583:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10584:          /* if(strb != endptr && *endptr == '\0') */
                   10585:          /*    dval=dlval; */
                   10586:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10587:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10588:            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);
                   10589:            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);
                   10590:            return 1;
                   10591:          }
                   10592:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10593:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10594:        }
                   10595:        strcpy(line,stra);
1.223     brouard  10596:       }/* end loop ntqv */
1.225     brouard  10597:       
1.223     brouard  10598:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10599:        cutv(stra, strb, line, ' '); 
                   10600:        if(strb[0]=='.') { /* Missing value */
                   10601:          lval=-1;
                   10602:        }else{
                   10603:          errno=0;
                   10604:          lval=strtol(strb,&endptr,10); 
                   10605:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10606:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10607:            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);
                   10608:            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);
                   10609:            return 1;
                   10610:          }
                   10611:        }
                   10612:        if(lval <-1 || lval >1){
                   10613:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10614:  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  10615:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10616:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10617:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10618:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10619:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10620:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10621:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10622:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10623:  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  10624:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10625:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10626:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10627:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10628:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10629:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10630:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10631:          return 1;
                   10632:        }
1.341     brouard  10633:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10634:        strcpy(line,stra);
1.223     brouard  10635:       }/* end loop ntv */
1.225     brouard  10636:       
1.223     brouard  10637:       /* Statuses  at wave */
1.137     brouard  10638:       cutv(stra, strb, line, ' '); 
1.223     brouard  10639:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10640:        lval=-1;
1.136     brouard  10641:       }else{
1.238     brouard  10642:        errno=0;
                   10643:        lval=strtol(strb,&endptr,10); 
                   10644:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10645:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10646:          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);
                   10647:          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);
                   10648:          return 1;
                   10649:        }
1.136     brouard  10650:       }
1.225     brouard  10651:       
1.136     brouard  10652:       s[j][i]=lval;
1.225     brouard  10653:       
1.223     brouard  10654:       /* Date of Interview */
1.136     brouard  10655:       strcpy(line,stra);
                   10656:       cutv(stra, strb,line,' ');
1.169     brouard  10657:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10658:       }
1.169     brouard  10659:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10660:        month=99;
                   10661:        year=9999;
1.136     brouard  10662:       }else{
1.225     brouard  10663:        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);
                   10664:        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);
                   10665:        return 1;
1.136     brouard  10666:       }
                   10667:       anint[j][i]= (double) year; 
1.302     brouard  10668:       mint[j][i]= (double)month;
                   10669:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10670:       /*       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]); */
                   10671:       /*       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]); */
                   10672:       /* } */
1.136     brouard  10673:       strcpy(line,stra);
1.223     brouard  10674:     } /* End loop on waves */
1.225     brouard  10675:     
1.223     brouard  10676:     /* Date of death */
1.136     brouard  10677:     cutv(stra, strb,line,' '); 
1.169     brouard  10678:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10679:     }
1.169     brouard  10680:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10681:       month=99;
                   10682:       year=9999;
                   10683:     }else{
1.141     brouard  10684:       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  10685:       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);
                   10686:       return 1;
1.136     brouard  10687:     }
                   10688:     andc[i]=(double) year; 
                   10689:     moisdc[i]=(double) month; 
                   10690:     strcpy(line,stra);
                   10691:     
1.223     brouard  10692:     /* Date of birth */
1.136     brouard  10693:     cutv(stra, strb,line,' '); 
1.169     brouard  10694:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10695:     }
1.169     brouard  10696:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10697:       month=99;
                   10698:       year=9999;
                   10699:     }else{
1.141     brouard  10700:       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);
                   10701:       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  10702:       return 1;
1.136     brouard  10703:     }
                   10704:     if (year==9999) {
1.141     brouard  10705:       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);
                   10706:       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  10707:       return 1;
                   10708:       
1.136     brouard  10709:     }
                   10710:     annais[i]=(double)(year);
1.302     brouard  10711:     moisnais[i]=(double)(month);
                   10712:     for (j=1;j<=maxwav;j++){
                   10713:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10714:        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]);
                   10715:        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]);
                   10716:       }
                   10717:     }
                   10718: 
1.136     brouard  10719:     strcpy(line,stra);
1.225     brouard  10720:     
1.223     brouard  10721:     /* Sample weight */
1.136     brouard  10722:     cutv(stra, strb,line,' '); 
                   10723:     errno=0;
                   10724:     dval=strtod(strb,&endptr); 
                   10725:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10726:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10727:       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  10728:       fflush(ficlog);
                   10729:       return 1;
                   10730:     }
                   10731:     weight[i]=dval; 
                   10732:     strcpy(line,stra);
1.225     brouard  10733:     
1.223     brouard  10734:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10735:       cutv(stra, strb, line, ' '); 
                   10736:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10737:        lval=-1;
1.311     brouard  10738:        coqvar[iv][i]=NAN; 
                   10739:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10740:       }else{
1.225     brouard  10741:        errno=0;
                   10742:        /* what_kind_of_number(strb); */
                   10743:        dval=strtod(strb,&endptr);
                   10744:        /* if(strb != endptr && *endptr == '\0') */
                   10745:        /*   dval=dlval; */
                   10746:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10747:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10748:          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);
                   10749:          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);
                   10750:          return 1;
                   10751:        }
                   10752:        coqvar[iv][i]=dval; 
1.226     brouard  10753:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10754:       }
                   10755:       strcpy(line,stra);
                   10756:     }/* end loop nqv */
1.136     brouard  10757:     
1.223     brouard  10758:     /* Covariate values */
1.136     brouard  10759:     for (j=ncovcol;j>=1;j--){
                   10760:       cutv(stra, strb,line,' '); 
1.223     brouard  10761:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10762:        lval=-1;
1.136     brouard  10763:       }else{
1.225     brouard  10764:        errno=0;
                   10765:        lval=strtol(strb,&endptr,10); 
                   10766:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10767:          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);
                   10768:          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);
                   10769:          return 1;
                   10770:        }
1.136     brouard  10771:       }
                   10772:       if(lval <-1 || lval >1){
1.225     brouard  10773:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10774:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10775:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10776:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10777:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10778:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10779:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10780:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10781:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10782:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10783:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10784:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10785:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10786:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10787:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10788:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10789:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10790:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10791:        return 1;
1.136     brouard  10792:       }
                   10793:       covar[j][i]=(double)(lval);
                   10794:       strcpy(line,stra);
                   10795:     }  
                   10796:     lstra=strlen(stra);
1.225     brouard  10797:     
1.136     brouard  10798:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10799:       stratrunc = &(stra[lstra-9]);
                   10800:       num[i]=atol(stratrunc);
                   10801:     }
                   10802:     else
                   10803:       num[i]=atol(stra);
                   10804:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10805:       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;}*/
                   10806:     
                   10807:     i=i+1;
                   10808:   } /* End loop reading  data */
1.225     brouard  10809:   
1.136     brouard  10810:   *imax=i-1; /* Number of individuals */
                   10811:   fclose(fic);
1.225     brouard  10812:   
1.136     brouard  10813:   return (0);
1.164     brouard  10814:   /* endread: */
1.225     brouard  10815:   printf("Exiting readdata: ");
                   10816:   fclose(fic);
                   10817:   return (1);
1.223     brouard  10818: }
1.126     brouard  10819: 
1.234     brouard  10820: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10821:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10822:   while (*p2 == ' ')
1.234     brouard  10823:     p2++; 
                   10824:   /* while ((*p1++ = *p2++) !=0) */
                   10825:   /*   ; */
                   10826:   /* do */
                   10827:   /*   while (*p2 == ' ') */
                   10828:   /*     p2++; */
                   10829:   /* while (*p1++ == *p2++); */
                   10830:   *stri=p2; 
1.145     brouard  10831: }
                   10832: 
1.330     brouard  10833: int decoderesult( char resultline[], int nres)
1.230     brouard  10834: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10835: {
1.235     brouard  10836:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10837:   char resultsav[MAXLINE];
1.330     brouard  10838:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10839:   /* int modelresult[MAXLINE]; */
1.230     brouard  10840:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10841: 
1.234     brouard  10842:   removefirstspace(&resultline);
1.332     brouard  10843:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10844: 
1.332     brouard  10845:   strcpy(resultsav,resultline);
1.342     brouard  10846:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  10847:   if (strlen(resultsav) >1){
1.334     brouard  10848:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10849:   }
1.253     brouard  10850:   if(j == 0){ /* Resultline but no = */
                   10851:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10852:     return (0);
                   10853:   }
1.234     brouard  10854:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10855:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
                   10856:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
1.332     brouard  10857:     /* return 1;*/
1.234     brouard  10858:   }
1.334     brouard  10859:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10860:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10861:       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  10862:       /* 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  10863:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10864:       /* If a blank, then strc="V4=" and strd='\0' */
                   10865:       if(strc[0]=='\0'){
                   10866:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10867:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10868:        return 1;
                   10869:       }
1.234     brouard  10870:     }else
                   10871:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10872:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10873:     
1.230     brouard  10874:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10875:     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  10876:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10877:     /* cptcovsel++;     */
                   10878:     if (nbocc(stra,'=') >0)
                   10879:       strcpy(resultsav,stra); /* and analyzes it */
                   10880:   }
1.235     brouard  10881:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10882:   /* 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  10883:   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  10884:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10885:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10886:       match=0;
1.318     brouard  10887:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10888:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10889:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10890:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10891:          break;
                   10892:        }
                   10893:       }
                   10894:       if(match == 0){
1.338     brouard  10895:        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]);
                   10896:        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  10897:        return 1;
1.234     brouard  10898:       }
1.332     brouard  10899:     }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*/
                   10900:       /* We feed resultmodel[k1]=k2; */
                   10901:       match=0;
                   10902:       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 */
                   10903:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10904:          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  10905:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  10906:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  10907:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10908:          break;
                   10909:        }
                   10910:       }
                   10911:       if(match == 0){
1.338     brouard  10912:        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]);
                   10913:        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  10914:       return 1;
                   10915:       }
                   10916:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10917:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10918:       match=0;
1.342     brouard  10919:       /* 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  10920:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10921:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10922:          /* modelresult[k2]=k1; */
1.342     brouard  10923:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  10924:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10925:        }
                   10926:       }
                   10927:       if(match == 0){
1.338     brouard  10928:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   10929:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10930:        return 1;
                   10931:       }
                   10932:       match=0;
                   10933:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10934:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10935:          /* modelresult[k2]=k1;*/
1.342     brouard  10936:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  10937:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10938:          break;
                   10939:        }
                   10940:       }
                   10941:       if(match == 0){
1.338     brouard  10942:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   10943:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10944:        return 1;
                   10945:       }
                   10946:     }/* End of testing */
1.333     brouard  10947:   }/* End loop cptcovt */
1.235     brouard  10948:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10949:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10950:   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)
                   10951:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10952:     match=0;
1.318     brouard  10953:     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  10954:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10955:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10956:          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  10957:          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  10958:          ++match;
                   10959:        }
                   10960:       }
                   10961:     }
                   10962:     if(match == 0){
1.338     brouard  10963:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10964:       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  10965:       return 1;
1.234     brouard  10966:     }else if(match > 1){
1.338     brouard  10967:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10968:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10969:       return 1;
1.234     brouard  10970:     }
                   10971:   }
1.334     brouard  10972:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10973:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10974:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10975:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10976:   /* 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*/
                   10977:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10978:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10979:   /*    1 0 0 0 */
                   10980:   /*    2 1 0 0 */
                   10981:   /*    3 0 1 0 */ 
1.330     brouard  10982:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10983:   /*    5 0 0 1 */
1.330     brouard  10984:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10985:   /*    7 0 1 1 */
                   10986:   /*    8 1 1 1 */
1.237     brouard  10987:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10988:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10989:   /* V5*age V5 known which value for nres?  */
                   10990:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10991:   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.
                   10992:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10993:     /* k counting number of combination of single dummies in the equation model */
                   10994:     /* k4 counting single dummies in the equation model */
                   10995:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  10996:     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  10997:        /* 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  10998:       /* 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  10999:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11000:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11001:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11002:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11003:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11004:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11005:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11006:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11007:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11008:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11009:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11010:       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  11011:       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  11012:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11013:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11014:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11015:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11016:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11017:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11018:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11019:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11020:       /* 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  11021:       k4++;;
1.331     brouard  11022:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11023:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11024:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11025:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11026:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11027:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11028:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11029:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11030:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11031:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11032:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11033:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11034:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11035:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11036:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11037:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11038:       /* 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  11039:       k4q++;;
1.331     brouard  11040:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   11041:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  11042:       /* Wrong we want the value of variable name Tvar[k1] */
                   11043:       
                   11044:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  11045:       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)*/
1.334     brouard  11046:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  11047:       precov[nres][k1]=Tvalsel[k3];
1.342     brouard  11048:       /* 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  11049:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  11050:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  11051:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11052:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  11053:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11054:       /* 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.331     brouard  11055:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  11056:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11057:       /* 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  11058:     }else{
1.332     brouard  11059:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11060:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11061:     }
                   11062:   }
1.234     brouard  11063:   
1.334     brouard  11064:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11065:   return (0);
                   11066: }
1.235     brouard  11067: 
1.230     brouard  11068: int decodemodel( char model[], int lastobs)
                   11069:  /**< This routine decodes the model and returns:
1.224     brouard  11070:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11071:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11072:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11073:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11074:        * - cptcovage number of covariates with age*products =2
                   11075:        * - cptcovs number of simple covariates
1.339     brouard  11076:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11077:        * - 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  11078:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11079:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11080:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11081:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11082:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11083:        */
1.319     brouard  11084: /* 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  11085: {
1.238     brouard  11086:   int i, j, k, ks, v;
1.227     brouard  11087:   int  j1, k1, k2, k3, k4;
1.136     brouard  11088:   char modelsav[80];
1.145     brouard  11089:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  11090:   char *strpt;
1.136     brouard  11091: 
1.145     brouard  11092:   /*removespace(model);*/
1.136     brouard  11093:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  11094:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11095:     if (strstr(model,"AGE") !=0){
1.192     brouard  11096:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11097:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11098:       return 1;
                   11099:     }
1.141     brouard  11100:     if (strstr(model,"v") !=0){
1.338     brouard  11101:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11102:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11103:       return 1;
                   11104:     }
1.187     brouard  11105:     strcpy(modelsav,model); 
                   11106:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11107:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11108:       if(strpt != model){
1.338     brouard  11109:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11110:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11111:  corresponding column of parameters.\n",model);
1.338     brouard  11112:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11113:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11114:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11115:        return 1;
1.225     brouard  11116:       }
1.187     brouard  11117:       nagesqr=1;
                   11118:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11119:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11120:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11121:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11122:       else 
1.234     brouard  11123:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11124:     }else
                   11125:       nagesqr=0;
                   11126:     if (strlen(modelsav) >1){
                   11127:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11128:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  11129:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  11130:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11131:                     * cst, age and age*age 
                   11132:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11133:       /* including age products which are counted in cptcovage.
                   11134:        * but the covariates which are products must be treated 
                   11135:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  11136:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   11137:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  11138:       
                   11139:       
1.187     brouard  11140:       /*   Design
                   11141:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11142:        *  <          ncovcol=8                >
                   11143:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11144:        *   k=  1    2      3       4     5       6      7        8
                   11145:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345   ! brouard  11146:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11147:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11148:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11149:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11150:        *  Tage[++cptcovage]=k
1.345   ! brouard  11151:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11152:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11153:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11154:        *  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
                   11155:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11156:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11157:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345   ! brouard  11158:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11159:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11160:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345   ! brouard  11161:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
        !          11162:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11163:        * p Tprod[1]@2={                         6, 5}
                   11164:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11165:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11166:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11167:        *How to reorganize? Tvars(orted)
1.187     brouard  11168:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11169:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11170:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11171:        * Struct []
                   11172:        */
1.225     brouard  11173:       
1.187     brouard  11174:       /* This loop fills the array Tvar from the string 'model'.*/
                   11175:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11176:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11177:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11178:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11179:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11180:       /*       k=1 Tvar[1]=2 (from V2) */
                   11181:       /*       k=5 Tvar[5] */
                   11182:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11183:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11184:       /*       } */
1.198     brouard  11185:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11186:       /*
                   11187:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11188:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11189:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11190:       }
1.187     brouard  11191:       cptcovage=0;
1.319     brouard  11192:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11193:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11194:                                         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" */
                   11195:        if (nbocc(modelsav,'+')==0)
                   11196:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11197:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11198:        /*scanf("%d",i);*/
1.319     brouard  11199:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   11200:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
1.234     brouard  11201:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   11202:            /* covar is not filled and then is empty */
                   11203:            cptcovprod--;
                   11204:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  11205:            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 */
1.234     brouard  11206:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  11207:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11208:            Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.234     brouard  11209:            /*printf("stre=%s ", stre);*/
                   11210:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   11211:            cptcovprod--;
                   11212:            cutl(stre,strb,strc,'V');
                   11213:            Tvar[k]=atoi(stre);
                   11214:            Typevar[k]=1;  /* 1 for age product */
                   11215:            cptcovage++;
                   11216:            Tage[cptcovage]=k;
                   11217:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11218:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11219:            cptcovn++;
                   11220:            cptcovprodnoage++;k1++;
                   11221:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11222:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11223:                                                because this model-covariate is a construction we invent a new column
                   11224:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11225:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11226:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11227:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11228:            /* Please remark that the new variables are model dependent */
                   11229:            /* If we have 4 variable but the model uses only 3, like in
                   11230:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11231:             *  k=     1     2       3   4     5        6        7       8
                   11232:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11233:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11234:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11235:             */
1.339     brouard  11236:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11237:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11238:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11239:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11240:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11241:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11242:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11243:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11244:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11245:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11246:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11247:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11248:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11249:            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 */
                   11250:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11251:              /* Computes the new covariate which is a product of
                   11252:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11253:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11254:              }
                   11255:            } /*End of FixedV */
1.234     brouard  11256:          } /* End age is not in the model */
                   11257:        } /* End if model includes a product */
1.319     brouard  11258:        else { /* not a product */
1.234     brouard  11259:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11260:          /*  scanf("%d",i);*/
                   11261:          cutl(strd,strc,strb,'V');
                   11262:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11263:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11264:          Tvar[k]=atoi(strd);
                   11265:          Typevar[k]=0;  /* 0 for simple covariates */
                   11266:        }
                   11267:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11268:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11269:                                  scanf("%d",i);*/
1.187     brouard  11270:       } /* end of loop + on total covariates */
                   11271:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11272:   } /* end if strlen(model == 0) */
1.136     brouard  11273:   
                   11274:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11275:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11276:   
1.136     brouard  11277:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11278:      printf("cptcovprod=%d ", cptcovprod);
                   11279:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11280:      scanf("%d ",i);*/
                   11281: 
                   11282: 
1.230     brouard  11283: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11284:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11285: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11286:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11287:    k =           1    2   3     4       5       6      7      8        9
                   11288:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11289:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11290:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11291:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11292:          Tmodelind[combination of covar]=k;
1.225     brouard  11293: */  
                   11294: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11295:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11296:   /* 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  11297:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11298:   printf("Model=1+age+%s\n\
1.227     brouard  11299: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11300: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11301: 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  11302:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11303: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11304: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11305: 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  11306:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11307:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.343     brouard  11308:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=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  11309:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11310:       Fixed[k]= 0;
                   11311:       Dummy[k]= 0;
1.225     brouard  11312:       ncoveff++;
1.232     brouard  11313:       ncovf++;
1.234     brouard  11314:       nsd++;
                   11315:       modell[k].maintype= FTYPE;
                   11316:       TvarsD[nsd]=Tvar[k];
                   11317:       TvarsDind[nsd]=k;
1.330     brouard  11318:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11319:       TvarF[ncovf]=Tvar[k];
                   11320:       TvarFind[ncovf]=k;
                   11321:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11322:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11323:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11324:     }else if( Tposprod[k]>0  &&  Typevar[k]==2 && 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 */
1.234     brouard  11325:       Fixed[k]= 0;
                   11326:       Dummy[k]= 0;
                   11327:       ncoveff++;
                   11328:       ncovf++;
                   11329:       modell[k].maintype= FTYPE;
                   11330:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11331:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11332:       TvarFind[ncovf]=k;
1.230     brouard  11333:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11334:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11335:     }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  11336:       Fixed[k]= 0;
                   11337:       Dummy[k]= 1;
1.230     brouard  11338:       nqfveff++;
1.234     brouard  11339:       modell[k].maintype= FTYPE;
                   11340:       modell[k].subtype= FQ;
                   11341:       nsq++;
1.334     brouard  11342:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11343:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11344:       ncovf++;
1.234     brouard  11345:       TvarF[ncovf]=Tvar[k];
                   11346:       TvarFind[ncovf]=k;
1.231     brouard  11347:       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  11348:       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  11349:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11350:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11351:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11352:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11353:       ncovvt++;
                   11354:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11355:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11356: 
1.227     brouard  11357:       Fixed[k]= 1;
                   11358:       Dummy[k]= 0;
1.225     brouard  11359:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11360:       modell[k].maintype= VTYPE;
                   11361:       modell[k].subtype= VD;
                   11362:       nsd++;
                   11363:       TvarsD[nsd]=Tvar[k];
                   11364:       TvarsDind[nsd]=k;
1.330     brouard  11365:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11366:       ncovv++; /* Only simple time varying variables */
                   11367:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11368:       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  11369:       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 */
                   11370:       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  11371:       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);
                   11372:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11373:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11374:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11375:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11376:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11377:       ncovvt++;
                   11378:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11379:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11380:       
1.234     brouard  11381:       Fixed[k]= 1;
                   11382:       Dummy[k]= 1;
                   11383:       nqtveff++;
                   11384:       modell[k].maintype= VTYPE;
                   11385:       modell[k].subtype= VQ;
                   11386:       ncovv++; /* Only simple time varying variables */
                   11387:       nsq++;
1.334     brouard  11388:       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) */
                   11389:       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  11390:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11391:       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  11392:       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 */
                   11393:       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  11394:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11395:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.342     brouard  11396:       /* printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv); */
                   11397:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11398:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11399:       ncova++;
                   11400:       TvarA[ncova]=Tvar[k];
                   11401:       TvarAind[ncova]=k;
1.231     brouard  11402:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11403:        Fixed[k]= 2;
                   11404:        Dummy[k]= 2;
                   11405:        modell[k].maintype= ATYPE;
                   11406:        modell[k].subtype= APFD;
                   11407:        /* ncoveff++; */
1.227     brouard  11408:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11409:        Fixed[k]= 2;
                   11410:        Dummy[k]= 3;
                   11411:        modell[k].maintype= ATYPE;
                   11412:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11413:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11414:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11415:        Fixed[k]= 3;
                   11416:        Dummy[k]= 2;
                   11417:        modell[k].maintype= ATYPE;
                   11418:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11419:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11420:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11421:        Fixed[k]= 3;
                   11422:        Dummy[k]= 3;
                   11423:        modell[k].maintype= ATYPE;
                   11424:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11425:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11426:       }
1.339     brouard  11427:     }else if (Typevar[k] == 2) {  /* product 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  */
                   11428:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11429:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11430:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11431:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1} k1=1 first product but second time varying because of V3 */
                   11432:       ncovvt++;
                   11433:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11434:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11435:       ncovvt++;
                   11436:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11437:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11438: 
                   11439: 
                   11440:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11441:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11442:          Fixed[k]= 1;
                   11443:          Dummy[k]= 0;
                   11444:          modell[k].maintype= FTYPE;
                   11445:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11446:          ncovf++; /* Fixed variables without age */
                   11447:          TvarF[ncovf]=Tvar[k];
                   11448:          TvarFind[ncovf]=k;
1.339     brouard  11449:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11450:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11451:          Dummy[k]= 1;
                   11452:          modell[k].maintype= FTYPE;
                   11453:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11454:          ncovf++; /* Varying variables without age */
                   11455:          TvarF[ncovf]=Tvar[k];
                   11456:          TvarFind[ncovf]=k;
1.339     brouard  11457:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11458:          Fixed[k]= 1;
                   11459:          Dummy[k]= 0;
                   11460:          modell[k].maintype= VTYPE;
                   11461:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11462:          ncovv++; /* Varying variables without age */
1.339     brouard  11463:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11464:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11465:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11466:          Fixed[k]= 1;
                   11467:          Dummy[k]= 1;
                   11468:          modell[k].maintype= VTYPE;
                   11469:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11470:          ncovv++; /* Varying variables without age */
                   11471:          TvarV[ncovv]=Tvar[k];
                   11472:          TvarVind[ncovv]=k;
                   11473:        }
1.339     brouard  11474:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11475:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11476:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11477:          Dummy[k]= 1;
                   11478:          modell[k].maintype= FTYPE;
                   11479:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11480:          ncovf++; /* Fixed variables without age */
                   11481:          TvarF[ncovf]=Tvar[k];
                   11482:          TvarFind[ncovf]=k;
1.339     brouard  11483:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11484:          Fixed[k]= 1;
                   11485:          Dummy[k]= 1;
                   11486:          modell[k].maintype= VTYPE;
                   11487:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11488:          ncovv++; /* Varying variables without age */
                   11489:          TvarV[ncovv]=Tvar[k];
                   11490:          TvarVind[ncovv]=k;
1.339     brouard  11491:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11492:          Fixed[k]= 1;
                   11493:          Dummy[k]= 1;
                   11494:          modell[k].maintype= VTYPE;
                   11495:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11496:          ncovv++; /* Varying variables without age */
                   11497:          TvarV[ncovv]=Tvar[k];
                   11498:          TvarVind[ncovv]=k;
                   11499:          ncovv++; /* Varying variables without age */
                   11500:          TvarV[ncovv]=Tvar[k];
                   11501:          TvarVind[ncovv]=k;
                   11502:        }
1.339     brouard  11503:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11504:        if(Tvard[k1][2] <=ncovcol){
                   11505:          Fixed[k]= 1;
                   11506:          Dummy[k]= 1;
                   11507:          modell[k].maintype= VTYPE;
                   11508:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11509:          ncovv++; /* Varying variables without age */
                   11510:          TvarV[ncovv]=Tvar[k];
                   11511:          TvarVind[ncovv]=k;
                   11512:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11513:          Fixed[k]= 1;
                   11514:          Dummy[k]= 1;
                   11515:          modell[k].maintype= VTYPE;
                   11516:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11517:          ncovv++; /* Varying variables without age */
                   11518:          TvarV[ncovv]=Tvar[k];
                   11519:          TvarVind[ncovv]=k;
                   11520:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11521:          Fixed[k]= 1;
                   11522:          Dummy[k]= 0;
                   11523:          modell[k].maintype= VTYPE;
                   11524:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11525:          ncovv++; /* Varying variables without age */
                   11526:          TvarV[ncovv]=Tvar[k];
                   11527:          TvarVind[ncovv]=k;
                   11528:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11529:          Fixed[k]= 1;
                   11530:          Dummy[k]= 1;
                   11531:          modell[k].maintype= VTYPE;
                   11532:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11533:          ncovv++; /* Varying variables without age */
                   11534:          TvarV[ncovv]=Tvar[k];
                   11535:          TvarVind[ncovv]=k;
                   11536:        }
1.339     brouard  11537:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11538:        if(Tvard[k1][2] <=ncovcol){
                   11539:          Fixed[k]= 1;
                   11540:          Dummy[k]= 1;
                   11541:          modell[k].maintype= VTYPE;
                   11542:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11543:          ncovv++; /* Varying variables without age */
                   11544:          TvarV[ncovv]=Tvar[k];
                   11545:          TvarVind[ncovv]=k;
                   11546:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11547:          Fixed[k]= 1;
                   11548:          Dummy[k]= 1;
                   11549:          modell[k].maintype= VTYPE;
                   11550:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11551:          ncovv++; /* Varying variables without age */
                   11552:          TvarV[ncovv]=Tvar[k];
                   11553:          TvarVind[ncovv]=k;
                   11554:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11555:          Fixed[k]= 1;
                   11556:          Dummy[k]= 1;
                   11557:          modell[k].maintype= VTYPE;
                   11558:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11559:          ncovv++; /* Varying variables without age */
                   11560:          TvarV[ncovv]=Tvar[k];
                   11561:          TvarVind[ncovv]=k;
                   11562:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11563:          Fixed[k]= 1;
                   11564:          Dummy[k]= 1;
                   11565:          modell[k].maintype= VTYPE;
                   11566:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11567:          ncovv++; /* Varying variables without age */
                   11568:          TvarV[ncovv]=Tvar[k];
                   11569:          TvarVind[ncovv]=k;
                   11570:        }
1.227     brouard  11571:       }else{
1.240     brouard  11572:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11573:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11574:       } /*end k1*/
1.225     brouard  11575:     }else{
1.226     brouard  11576:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11577:       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  11578:     }
1.342     brouard  11579:     /* 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]); */
                   11580:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  11581:     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]);
                   11582:   }
                   11583:   /* Searching for doublons in the model */
                   11584:   for(k1=1; k1<= cptcovt;k1++){
                   11585:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11586:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11587:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11588:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11589:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11590:            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]);
                   11591:            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  11592:            return(1);
                   11593:          }
                   11594:        }else if (Typevar[k1] ==2){
                   11595:          k3=Tposprod[k1];
                   11596:          k4=Tposprod[k2];
                   11597:          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  11598:            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]]);
                   11599:            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  11600:            return(1);
                   11601:          }
                   11602:        }
1.227     brouard  11603:       }
                   11604:     }
1.225     brouard  11605:   }
                   11606:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11607:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11608:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11609:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11610:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11611:   /*endread:*/
1.225     brouard  11612:   printf("Exiting decodemodel: ");
                   11613:   return (1);
1.136     brouard  11614: }
                   11615: 
1.169     brouard  11616: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11617: {/* Check ages at death */
1.136     brouard  11618:   int i, m;
1.218     brouard  11619:   int firstone=0;
                   11620:   
1.136     brouard  11621:   for (i=1; i<=imx; i++) {
                   11622:     for(m=2; (m<= maxwav); m++) {
                   11623:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11624:        anint[m][i]=9999;
1.216     brouard  11625:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11626:          s[m][i]=-1;
1.136     brouard  11627:       }
                   11628:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11629:        *nberr = *nberr + 1;
1.218     brouard  11630:        if(firstone == 0){
                   11631:          firstone=1;
1.260     brouard  11632:        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  11633:        }
1.262     brouard  11634:        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  11635:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11636:       }
                   11637:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11638:        (*nberr)++;
1.259     brouard  11639:        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  11640:        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  11641:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11642:       }
                   11643:     }
                   11644:   }
                   11645: 
                   11646:   for (i=1; i<=imx; i++)  {
                   11647:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11648:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11649:       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  11650:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11651:          if(agedc[i]>0){
                   11652:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11653:              agev[m][i]=agedc[i];
1.214     brouard  11654:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11655:            }else {
1.136     brouard  11656:              if ((int)andc[i]!=9999){
                   11657:                nbwarn++;
                   11658:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11659:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11660:                agev[m][i]=-1;
                   11661:              }
                   11662:            }
1.169     brouard  11663:          } /* agedc > 0 */
1.214     brouard  11664:        } /* end if */
1.136     brouard  11665:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11666:                                 years but with the precision of a month */
                   11667:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11668:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11669:            agev[m][i]=1;
                   11670:          else if(agev[m][i] < *agemin){ 
                   11671:            *agemin=agev[m][i];
                   11672:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11673:          }
                   11674:          else if(agev[m][i] >*agemax){
                   11675:            *agemax=agev[m][i];
1.156     brouard  11676:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11677:          }
                   11678:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11679:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11680:        } /* en if 9*/
1.136     brouard  11681:        else { /* =9 */
1.214     brouard  11682:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11683:          agev[m][i]=1;
                   11684:          s[m][i]=-1;
                   11685:        }
                   11686:       }
1.214     brouard  11687:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11688:        agev[m][i]=1;
1.214     brouard  11689:       else{
                   11690:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11691:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11692:        agev[m][i]=0;
                   11693:       }
                   11694:     } /* End for lastpass */
                   11695:   }
1.136     brouard  11696:     
                   11697:   for (i=1; i<=imx; i++)  {
                   11698:     for(m=firstpass; (m<=lastpass); m++){
                   11699:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11700:        (*nberr)++;
1.136     brouard  11701:        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);     
                   11702:        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);     
                   11703:        return 1;
                   11704:       }
                   11705:     }
                   11706:   }
                   11707: 
                   11708:   /*for (i=1; i<=imx; i++){
                   11709:   for (m=firstpass; (m<lastpass); m++){
                   11710:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11711: }
                   11712: 
                   11713: }*/
                   11714: 
                   11715: 
1.139     brouard  11716:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11717:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11718: 
                   11719:   return (0);
1.164     brouard  11720:  /* endread:*/
1.136     brouard  11721:     printf("Exiting calandcheckages: ");
                   11722:     return (1);
                   11723: }
                   11724: 
1.172     brouard  11725: #if defined(_MSC_VER)
                   11726: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11727: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11728: //#include "stdafx.h"
                   11729: //#include <stdio.h>
                   11730: //#include <tchar.h>
                   11731: //#include <windows.h>
                   11732: //#include <iostream>
                   11733: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11734: 
                   11735: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11736: 
                   11737: BOOL IsWow64()
                   11738: {
                   11739:        BOOL bIsWow64 = FALSE;
                   11740: 
                   11741:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11742:        //  (HANDLE, PBOOL);
                   11743: 
                   11744:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11745: 
                   11746:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11747:        const char funcName[] = "IsWow64Process";
                   11748:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11749:                GetProcAddress(module, funcName);
                   11750: 
                   11751:        if (NULL != fnIsWow64Process)
                   11752:        {
                   11753:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11754:                        &bIsWow64))
                   11755:                        //throw std::exception("Unknown error");
                   11756:                        printf("Unknown error\n");
                   11757:        }
                   11758:        return bIsWow64 != FALSE;
                   11759: }
                   11760: #endif
1.177     brouard  11761: 
1.191     brouard  11762: void syscompilerinfo(int logged)
1.292     brouard  11763: {
                   11764: #include <stdint.h>
                   11765: 
                   11766:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11767:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11768:    /* /GS /W3 /Gy
                   11769:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11770:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11771:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11772:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11773:    */ 
                   11774:    /* 64 bits */
1.185     brouard  11775:    /*
                   11776:      /GS /W3 /Gy
                   11777:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11778:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11779:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11780:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11781:    /* Optimization are useless and O3 is slower than O2 */
                   11782:    /*
                   11783:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11784:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11785:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11786:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11787:    */
1.186     brouard  11788:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11789:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11790:       /PDB:"visual studio
                   11791:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11792:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11793:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11794:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11795:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11796:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11797:       uiAccess='false'"
                   11798:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11799:       /NOLOGO /TLBID:1
                   11800:    */
1.292     brouard  11801: 
                   11802: 
1.177     brouard  11803: #if defined __INTEL_COMPILER
1.178     brouard  11804: #if defined(__GNUC__)
                   11805:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11806: #endif
1.177     brouard  11807: #elif defined(__GNUC__) 
1.179     brouard  11808: #ifndef  __APPLE__
1.174     brouard  11809: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11810: #endif
1.177     brouard  11811:    struct utsname sysInfo;
1.178     brouard  11812:    int cross = CROSS;
                   11813:    if (cross){
                   11814:           printf("Cross-");
1.191     brouard  11815:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11816:    }
1.174     brouard  11817: #endif
                   11818: 
1.191     brouard  11819:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11820: #if defined(__clang__)
1.191     brouard  11821:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11822: #endif
                   11823: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11824:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11825: #endif
                   11826: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11827:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11828: #endif
                   11829: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11830:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11831: #endif
                   11832: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11833:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11834: #endif
                   11835: #if defined(_MSC_VER)
1.191     brouard  11836:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11837: #endif
                   11838: #if defined(__PGI)
1.191     brouard  11839:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11840: #endif
                   11841: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11842:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11843: #endif
1.191     brouard  11844:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11845:    
1.167     brouard  11846: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11847: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11848:     // Windows (x64 and x86)
1.191     brouard  11849:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11850: #elif __unix__ // all unices, not all compilers
                   11851:     // Unix
1.191     brouard  11852:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11853: #elif __linux__
                   11854:     // linux
1.191     brouard  11855:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11856: #elif __APPLE__
1.174     brouard  11857:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11858:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11859: #endif
                   11860: 
                   11861: /*  __MINGW32__          */
                   11862: /*  __CYGWIN__  */
                   11863: /* __MINGW64__  */
                   11864: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11865: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11866: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11867: /* _WIN64  // Defined for applications for Win64. */
                   11868: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11869: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11870: 
1.167     brouard  11871: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11872:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11873: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11874:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11875: #else
1.191     brouard  11876:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11877: #endif
                   11878: 
1.169     brouard  11879: #if defined(__GNUC__)
                   11880: # if defined(__GNUC_PATCHLEVEL__)
                   11881: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11882:                             + __GNUC_MINOR__ * 100 \
                   11883:                             + __GNUC_PATCHLEVEL__)
                   11884: # else
                   11885: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11886:                             + __GNUC_MINOR__ * 100)
                   11887: # endif
1.174     brouard  11888:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11889:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11890: 
                   11891:    if (uname(&sysInfo) != -1) {
                   11892:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11893:         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  11894:    }
                   11895:    else
                   11896:       perror("uname() error");
1.179     brouard  11897:    //#ifndef __INTEL_COMPILER 
                   11898: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11899:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11900:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11901: #endif
1.169     brouard  11902: #endif
1.172     brouard  11903: 
1.286     brouard  11904:    //   void main ()
1.172     brouard  11905:    //   {
1.169     brouard  11906: #if defined(_MSC_VER)
1.174     brouard  11907:    if (IsWow64()){
1.191     brouard  11908:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11909:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11910:    }
                   11911:    else{
1.191     brouard  11912:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11913:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11914:    }
1.172     brouard  11915:    //     printf("\nPress Enter to continue...");
                   11916:    //     getchar();
                   11917:    //   }
                   11918: 
1.169     brouard  11919: #endif
                   11920:    
1.167     brouard  11921: 
1.219     brouard  11922: }
1.136     brouard  11923: 
1.219     brouard  11924: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11925:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11926:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11927:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11928:   /* double ftolpl = 1.e-10; */
1.180     brouard  11929:   double age, agebase, agelim;
1.203     brouard  11930:   double tot;
1.180     brouard  11931: 
1.202     brouard  11932:   strcpy(filerespl,"PL_");
                   11933:   strcat(filerespl,fileresu);
                   11934:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11935:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11936:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11937:   }
1.288     brouard  11938:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11939:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11940:   pstamp(ficrespl);
1.288     brouard  11941:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11942:   fprintf(ficrespl,"#Age ");
                   11943:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11944:   fprintf(ficrespl,"\n");
1.180     brouard  11945:   
1.219     brouard  11946:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11947: 
1.219     brouard  11948:   agebase=ageminpar;
                   11949:   agelim=agemaxpar;
1.180     brouard  11950: 
1.227     brouard  11951:   /* i1=pow(2,ncoveff); */
1.234     brouard  11952:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11953:   if (cptcovn < 1){i1=1;}
1.180     brouard  11954: 
1.337     brouard  11955:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11956:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11957:       k=TKresult[nres];
1.338     brouard  11958:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11959:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11960:       /*       continue; */
1.235     brouard  11961: 
1.238     brouard  11962:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11963:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11964:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11965:       /* k=k+1; */
                   11966:       /* to clean */
1.332     brouard  11967:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11968:       fprintf(ficrespl,"#******");
                   11969:       printf("#******");
                   11970:       fprintf(ficlog,"#******");
1.337     brouard  11971:       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  11972:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11973:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11974:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11975:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11976:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11977:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11978:       }
                   11979:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11980:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11981:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11982:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11983:       /* } */
1.238     brouard  11984:       fprintf(ficrespl,"******\n");
                   11985:       printf("******\n");
                   11986:       fprintf(ficlog,"******\n");
                   11987:       if(invalidvarcomb[k]){
                   11988:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11989:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11990:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11991:        continue;
                   11992:       }
1.219     brouard  11993: 
1.238     brouard  11994:       fprintf(ficrespl,"#Age ");
1.337     brouard  11995:       /* for(j=1;j<=cptcoveff;j++) { */
                   11996:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11997:       /* } */
                   11998:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   11999:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12000:       }
                   12001:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12002:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12003:     
1.238     brouard  12004:       for (age=agebase; age<=agelim; age++){
                   12005:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12006:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12007:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12008:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12009:        /* for(j=1;j<=cptcoveff;j++) */
                   12010:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12011:        for(j=1;j<=cptcovs;j++)
                   12012:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12013:        tot=0.;
                   12014:        for(i=1; i<=nlstate;i++){
                   12015:          tot +=  prlim[i][i];
                   12016:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12017:        }
                   12018:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12019:       } /* Age */
                   12020:       /* was end of cptcod */
1.337     brouard  12021:     } /* nres */
                   12022:   /* } /\* for each combination *\/ */
1.219     brouard  12023:   return 0;
1.180     brouard  12024: }
                   12025: 
1.218     brouard  12026: 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  12027:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12028:        
                   12029:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12030:    * at any age between ageminpar and agemaxpar
                   12031:         */
1.235     brouard  12032:   int i, j, k, i1, nres=0 ;
1.217     brouard  12033:   /* double ftolpl = 1.e-10; */
                   12034:   double age, agebase, agelim;
                   12035:   double tot;
1.218     brouard  12036:   /* double ***mobaverage; */
                   12037:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12038: 
                   12039:   strcpy(fileresplb,"PLB_");
                   12040:   strcat(fileresplb,fileresu);
                   12041:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12042:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12043:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12044:   }
1.288     brouard  12045:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12046:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12047:   pstamp(ficresplb);
1.288     brouard  12048:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12049:   fprintf(ficresplb,"#Age ");
                   12050:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12051:   fprintf(ficresplb,"\n");
                   12052:   
1.218     brouard  12053:   
                   12054:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12055:   
                   12056:   agebase=ageminpar;
                   12057:   agelim=agemaxpar;
                   12058:   
                   12059:   
1.227     brouard  12060:   i1=pow(2,cptcoveff);
1.218     brouard  12061:   if (cptcovn < 1){i1=1;}
1.227     brouard  12062:   
1.238     brouard  12063:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12064:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12065:       k=TKresult[nres];
                   12066:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12067:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12068:      /*        continue; */
                   12069:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12070:       fprintf(ficresplb,"#******");
                   12071:       printf("#******");
                   12072:       fprintf(ficlog,"#******");
1.338     brouard  12073:       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) */
                   12074:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12075:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12076:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12077:       }
1.338     brouard  12078:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12079:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12080:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12081:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12082:       /* } */
                   12083:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12084:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12085:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12086:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12087:       /* } */
1.238     brouard  12088:       fprintf(ficresplb,"******\n");
                   12089:       printf("******\n");
                   12090:       fprintf(ficlog,"******\n");
                   12091:       if(invalidvarcomb[k]){
                   12092:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12093:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12094:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12095:        continue;
                   12096:       }
1.218     brouard  12097:     
1.238     brouard  12098:       fprintf(ficresplb,"#Age ");
1.338     brouard  12099:       for(j=1;j<=cptcovs;j++) {
                   12100:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12101:       }
                   12102:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12103:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12104:     
                   12105:     
1.238     brouard  12106:       for (age=agebase; age<=agelim; age++){
                   12107:        /* for (age=agebase; age<=agebase; age++){ */
                   12108:        if(mobilavproj > 0){
                   12109:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12110:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12111:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12112:        }else if (mobilavproj == 0){
                   12113:          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);
                   12114:          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);
                   12115:          exit(1);
                   12116:        }else{
                   12117:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12118:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12119:          /* printf("TOTOT\n"); */
                   12120:           /* exit(1); */
1.238     brouard  12121:        }
                   12122:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12123:        for(j=1;j<=cptcovs;j++)
                   12124:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12125:        tot=0.;
                   12126:        for(i=1; i<=nlstate;i++){
                   12127:          tot +=  bprlim[i][i];
                   12128:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12129:        }
                   12130:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12131:       } /* Age */
                   12132:       /* was end of cptcod */
1.255     brouard  12133:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12134:     /* } /\* end of any combination *\/ */
1.238     brouard  12135:   } /* end of nres */  
1.218     brouard  12136:   /* hBijx(p, bage, fage); */
                   12137:   /* fclose(ficrespijb); */
                   12138:   
                   12139:   return 0;
1.217     brouard  12140: }
1.218     brouard  12141:  
1.180     brouard  12142: int hPijx(double *p, int bage, int fage){
                   12143:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12144:   /* to be optimized with precov */
1.180     brouard  12145:   int stepsize;
                   12146:   int agelim;
                   12147:   int hstepm;
                   12148:   int nhstepm;
1.235     brouard  12149:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12150: 
                   12151:   double agedeb;
                   12152:   double ***p3mat;
                   12153: 
1.337     brouard  12154:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12155:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12156:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12157:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12158:   }
                   12159:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12160:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12161:   
                   12162:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12163:   /*if (stepm<=24) stepsize=2;*/
                   12164:   
                   12165:   agelim=AGESUP;
                   12166:   hstepm=stepsize*YEARM; /* Every year of age */
                   12167:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12168:   
                   12169:   /* hstepm=1;   aff par mois*/
                   12170:   pstamp(ficrespij);
                   12171:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12172:   i1= pow(2,cptcoveff);
                   12173:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12174:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12175:   /*   k=k+1;  */
                   12176:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12177:     k=TKresult[nres];
1.338     brouard  12178:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12179:     /* for(k=1; k<=i1;k++){ */
                   12180:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12181:     /*         continue; */
                   12182:     fprintf(ficrespij,"\n#****** ");
                   12183:     for(j=1;j<=cptcovs;j++){
                   12184:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12185:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12186:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12187:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12188:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12189:     }
                   12190:     fprintf(ficrespij,"******\n");
                   12191:     
                   12192:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12193:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12194:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12195:       
                   12196:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12197:       
                   12198:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12199:       oldm=oldms;savm=savms;
                   12200:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12201:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12202:       for(i=1; i<=nlstate;i++)
                   12203:        for(j=1; j<=nlstate+ndeath;j++)
                   12204:          fprintf(ficrespij," %1d-%1d",i,j);
                   12205:       fprintf(ficrespij,"\n");
                   12206:       for (h=0; h<=nhstepm; h++){
                   12207:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12208:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12209:        for(i=1; i<=nlstate;i++)
                   12210:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12211:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12212:        fprintf(ficrespij,"\n");
                   12213:       }
1.337     brouard  12214:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12215:       fprintf(ficrespij,"\n");
1.180     brouard  12216:     }
1.337     brouard  12217:   }
                   12218:   /*}*/
                   12219:   return 0;
1.180     brouard  12220: }
1.218     brouard  12221:  
                   12222:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12223:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12224:     /* To be optimized with precov */
1.217     brouard  12225:   int stepsize;
1.218     brouard  12226:   /* int agelim; */
                   12227:        int ageminl;
1.217     brouard  12228:   int hstepm;
                   12229:   int nhstepm;
1.238     brouard  12230:   int h, i, i1, j, k, nres;
1.218     brouard  12231:        
1.217     brouard  12232:   double agedeb;
                   12233:   double ***p3mat;
1.218     brouard  12234:        
                   12235:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12236:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12237:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12238:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12239:   }
                   12240:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12241:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12242:   
                   12243:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12244:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12245:   
1.218     brouard  12246:   /* agelim=AGESUP; */
1.289     brouard  12247:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12248:   hstepm=stepsize*YEARM; /* Every year of age */
                   12249:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12250:   
                   12251:   /* hstepm=1;   aff par mois*/
                   12252:   pstamp(ficrespijb);
1.255     brouard  12253:   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  12254:   i1= pow(2,cptcoveff);
1.218     brouard  12255:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12256:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12257:   /*   k=k+1;  */
1.238     brouard  12258:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12259:     k=TKresult[nres];
1.338     brouard  12260:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12261:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12262:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12263:     /*         continue; */
                   12264:     fprintf(ficrespijb,"\n#****** ");
                   12265:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12266:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12267:       /* for(j=1;j<=cptcoveff;j++) */
                   12268:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12269:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12270:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12271:     }
                   12272:     fprintf(ficrespijb,"******\n");
                   12273:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12274:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12275:       continue;
                   12276:     }
                   12277:     
                   12278:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12279:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12280:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12281:       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 */
                   12282:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12283:       
                   12284:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12285:       
                   12286:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12287:       /* and memory limitations if stepm is small */
                   12288:       
                   12289:       /* oldm=oldms;savm=savms; */
                   12290:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12291:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12292:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12293:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12294:       for(i=1; i<=nlstate;i++)
                   12295:        for(j=1; j<=nlstate+ndeath;j++)
                   12296:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12297:       fprintf(ficrespijb,"\n");
                   12298:       for (h=0; h<=nhstepm; h++){
                   12299:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12300:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12301:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12302:        for(i=1; i<=nlstate;i++)
                   12303:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12304:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12305:        fprintf(ficrespijb,"\n");
1.337     brouard  12306:       }
                   12307:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12308:       fprintf(ficrespijb,"\n");
                   12309:     } /* end age deb */
                   12310:     /* } /\* end combination *\/ */
1.238     brouard  12311:   } /* end nres */
1.218     brouard  12312:   return 0;
                   12313:  } /*  hBijx */
1.217     brouard  12314: 
1.180     brouard  12315: 
1.136     brouard  12316: /***********************************************/
                   12317: /**************** Main Program *****************/
                   12318: /***********************************************/
                   12319: 
                   12320: int main(int argc, char *argv[])
                   12321: {
                   12322: #ifdef GSL
                   12323:   const gsl_multimin_fminimizer_type *T;
                   12324:   size_t iteri = 0, it;
                   12325:   int rval = GSL_CONTINUE;
                   12326:   int status = GSL_SUCCESS;
                   12327:   double ssval;
                   12328: #endif
                   12329:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12330:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12331:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12332:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12333:   int jj, ll, li, lj, lk;
1.136     brouard  12334:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12335:   int num_filled;
1.136     brouard  12336:   int itimes;
                   12337:   int NDIM=2;
                   12338:   int vpopbased=0;
1.235     brouard  12339:   int nres=0;
1.258     brouard  12340:   int endishere=0;
1.277     brouard  12341:   int noffset=0;
1.274     brouard  12342:   int ncurrv=0; /* Temporary variable */
                   12343:   
1.164     brouard  12344:   char ca[32], cb[32];
1.136     brouard  12345:   /*  FILE *fichtm; *//* Html File */
                   12346:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12347:   struct stat info;
1.191     brouard  12348:   double agedeb=0.;
1.194     brouard  12349: 
                   12350:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12351:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12352: 
1.165     brouard  12353:   double fret;
1.191     brouard  12354:   double dum=0.; /* Dummy variable */
1.136     brouard  12355:   double ***p3mat;
1.218     brouard  12356:   /* double ***mobaverage; */
1.319     brouard  12357:   double wald;
1.164     brouard  12358: 
                   12359:   char line[MAXLINE];
1.197     brouard  12360:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12361: 
1.234     brouard  12362:   char  modeltemp[MAXLINE];
1.332     brouard  12363:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12364:   
1.136     brouard  12365:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12366:   char *tok, *val; /* pathtot */
1.334     brouard  12367:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12368:   int c,  h , cpt, c2;
1.191     brouard  12369:   int jl=0;
                   12370:   int i1, j1, jk, stepsize=0;
1.194     brouard  12371:   int count=0;
                   12372: 
1.164     brouard  12373:   int *tab; 
1.136     brouard  12374:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12375:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12376:   /* double anprojf, mprojf, jprojf; */
                   12377:   /* double jintmean,mintmean,aintmean;   */
                   12378:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12379:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12380:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12381:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12382:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12383:   int mobilav=0,popforecast=0;
1.191     brouard  12384:   int hstepm=0, nhstepm=0;
1.136     brouard  12385:   int agemortsup;
                   12386:   float  sumlpop=0.;
                   12387:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12388:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12389: 
1.191     brouard  12390:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12391:   double ftolpl=FTOL;
                   12392:   double **prlim;
1.217     brouard  12393:   double **bprlim;
1.317     brouard  12394:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12395:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12396:   double ***paramstart; /* Matrix of starting parameter values */
                   12397:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12398:   double **matcov; /* Matrix of covariance */
1.203     brouard  12399:   double **hess; /* Hessian matrix */
1.136     brouard  12400:   double ***delti3; /* Scale */
                   12401:   double *delti; /* Scale */
                   12402:   double ***eij, ***vareij;
                   12403:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12404: 
1.136     brouard  12405:   double *epj, vepp;
1.164     brouard  12406: 
1.273     brouard  12407:   double dateprev1, dateprev2;
1.296     brouard  12408:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12409:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12410: 
1.217     brouard  12411: 
1.136     brouard  12412:   double **ximort;
1.145     brouard  12413:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12414:   int *dcwave;
                   12415: 
1.164     brouard  12416:   char z[1]="c";
1.136     brouard  12417: 
                   12418:   /*char  *strt;*/
                   12419:   char strtend[80];
1.126     brouard  12420: 
1.164     brouard  12421: 
1.126     brouard  12422: /*   setlocale (LC_ALL, ""); */
                   12423: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12424: /*   textdomain (PACKAGE); */
                   12425: /*   setlocale (LC_CTYPE, ""); */
                   12426: /*   setlocale (LC_MESSAGES, ""); */
                   12427: 
                   12428:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12429:   rstart_time = time(NULL);  
                   12430:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12431:   start_time = *localtime(&rstart_time);
1.126     brouard  12432:   curr_time=start_time;
1.157     brouard  12433:   /*tml = *localtime(&start_time.tm_sec);*/
                   12434:   /* strcpy(strstart,asctime(&tml)); */
                   12435:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12436: 
                   12437: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12438: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12439: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12440: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12441: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12442: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12443: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12444: /*   strt=asctime(&tmg); */
                   12445: /*   printf("Time(after) =%s",strstart);  */
                   12446: /*  (void) time (&time_value);
                   12447: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12448: *  tm = *localtime(&time_value);
                   12449: *  strstart=asctime(&tm);
                   12450: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12451: */
                   12452: 
                   12453:   nberr=0; /* Number of errors and warnings */
                   12454:   nbwarn=0;
1.184     brouard  12455: #ifdef WIN32
                   12456:   _getcwd(pathcd, size);
                   12457: #else
1.126     brouard  12458:   getcwd(pathcd, size);
1.184     brouard  12459: #endif
1.191     brouard  12460:   syscompilerinfo(0);
1.196     brouard  12461:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12462:   if(argc <=1){
                   12463:     printf("\nEnter the parameter file name: ");
1.205     brouard  12464:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12465:       printf("ERROR Empty parameter file name\n");
                   12466:       goto end;
                   12467:     }
1.126     brouard  12468:     i=strlen(pathr);
                   12469:     if(pathr[i-1]=='\n')
                   12470:       pathr[i-1]='\0';
1.156     brouard  12471:     i=strlen(pathr);
1.205     brouard  12472:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12473:       pathr[i-1]='\0';
1.205     brouard  12474:     }
                   12475:     i=strlen(pathr);
                   12476:     if( i==0 ){
                   12477:       printf("ERROR Empty parameter file name\n");
                   12478:       goto end;
                   12479:     }
                   12480:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12481:       printf("Pathr |%s|\n",pathr);
                   12482:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12483:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12484:       strcpy (pathtot, val);
                   12485:       if(pathr[0] == '\0') break; /* Dirty */
                   12486:     }
                   12487:   }
1.281     brouard  12488:   else if (argc<=2){
                   12489:     strcpy(pathtot,argv[1]);
                   12490:   }
1.126     brouard  12491:   else{
                   12492:     strcpy(pathtot,argv[1]);
1.281     brouard  12493:     strcpy(z,argv[2]);
                   12494:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12495:   }
                   12496:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12497:   /*cygwin_split_path(pathtot,path,optionfile);
                   12498:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12499:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12500: 
                   12501:   /* Split argv[0], imach program to get pathimach */
                   12502:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12503:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12504:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12505:  /*   strcpy(pathimach,argv[0]); */
                   12506:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12507:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12508:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12509: #ifdef WIN32
                   12510:   _chdir(path); /* Can be a relative path */
                   12511:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12512: #else
1.126     brouard  12513:   chdir(path); /* Can be a relative path */
1.184     brouard  12514:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12515: #endif
                   12516:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12517:   strcpy(command,"mkdir ");
                   12518:   strcat(command,optionfilefiname);
                   12519:   if((outcmd=system(command)) != 0){
1.169     brouard  12520:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12521:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12522:     /* fclose(ficlog); */
                   12523: /*     exit(1); */
                   12524:   }
                   12525: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12526: /*     perror("mkdir"); */
                   12527: /*   } */
                   12528: 
                   12529:   /*-------- arguments in the command line --------*/
                   12530: 
1.186     brouard  12531:   /* Main Log file */
1.126     brouard  12532:   strcat(filelog, optionfilefiname);
                   12533:   strcat(filelog,".log");    /* */
                   12534:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12535:     printf("Problem with logfile %s\n",filelog);
                   12536:     goto end;
                   12537:   }
                   12538:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12539:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12540:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12541:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12542:  path=%s \n\
                   12543:  optionfile=%s\n\
                   12544:  optionfilext=%s\n\
1.156     brouard  12545:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12546: 
1.197     brouard  12547:   syscompilerinfo(1);
1.167     brouard  12548: 
1.126     brouard  12549:   printf("Local time (at start):%s",strstart);
                   12550:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12551:   fflush(ficlog);
                   12552: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12553: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12554: 
                   12555:   /* */
                   12556:   strcpy(fileres,"r");
                   12557:   strcat(fileres, optionfilefiname);
1.201     brouard  12558:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12559:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12560:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12561: 
1.186     brouard  12562:   /* Main ---------arguments file --------*/
1.126     brouard  12563: 
                   12564:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12565:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12566:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12567:     fflush(ficlog);
1.149     brouard  12568:     /* goto end; */
                   12569:     exit(70); 
1.126     brouard  12570:   }
                   12571: 
                   12572:   strcpy(filereso,"o");
1.201     brouard  12573:   strcat(filereso,fileresu);
1.126     brouard  12574:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12575:     printf("Problem with Output resultfile: %s\n", filereso);
                   12576:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12577:     fflush(ficlog);
                   12578:     goto end;
                   12579:   }
1.278     brouard  12580:       /*-------- Rewriting parameter file ----------*/
                   12581:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12582:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12583:   strcat(rfileres,".");    /* */
                   12584:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12585:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12586:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12587:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12588:     fflush(ficlog);
                   12589:     goto end;
                   12590:   }
                   12591:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12592: 
1.278     brouard  12593:                                      
1.126     brouard  12594:   /* Reads comments: lines beginning with '#' */
                   12595:   numlinepar=0;
1.277     brouard  12596:   /* Is it a BOM UTF-8 Windows file? */
                   12597:   /* First parameter line */
1.197     brouard  12598:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12599:     noffset=0;
                   12600:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12601:     {
                   12602:       noffset=noffset+3;
                   12603:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12604:     }
1.302     brouard  12605: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12606:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12607:     {
                   12608:       noffset=noffset+2;
                   12609:       printf("# File is an UTF16BE BOM file\n");
                   12610:     }
                   12611:     else if( line[0] == 0 && line[1] == 0)
                   12612:     {
                   12613:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12614:        noffset=noffset+4;
                   12615:        printf("# File is an UTF16BE BOM file\n");
                   12616:       }
                   12617:     } else{
                   12618:       ;/*printf(" Not a BOM file\n");*/
                   12619:     }
                   12620:   
1.197     brouard  12621:     /* If line starts with a # it is a comment */
1.277     brouard  12622:     if (line[noffset] == '#') {
1.197     brouard  12623:       numlinepar++;
                   12624:       fputs(line,stdout);
                   12625:       fputs(line,ficparo);
1.278     brouard  12626:       fputs(line,ficres);
1.197     brouard  12627:       fputs(line,ficlog);
                   12628:       continue;
                   12629:     }else
                   12630:       break;
                   12631:   }
                   12632:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12633:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12634:     if (num_filled != 5) {
                   12635:       printf("Should be 5 parameters\n");
1.283     brouard  12636:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12637:     }
1.126     brouard  12638:     numlinepar++;
1.197     brouard  12639:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12640:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12641:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12642:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12643:   }
                   12644:   /* Second parameter line */
                   12645:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12646:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12647:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12648:     if (line[0] == '#') {
                   12649:       numlinepar++;
1.283     brouard  12650:       printf("%s",line);
                   12651:       fprintf(ficres,"%s",line);
                   12652:       fprintf(ficparo,"%s",line);
                   12653:       fprintf(ficlog,"%s",line);
1.197     brouard  12654:       continue;
                   12655:     }else
                   12656:       break;
                   12657:   }
1.223     brouard  12658:   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", \
                   12659:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12660:     if (num_filled != 11) {
                   12661:       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  12662:       printf("but line=%s\n",line);
1.283     brouard  12663:       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");
                   12664:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12665:     }
1.286     brouard  12666:     if( lastpass > maxwav){
                   12667:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12668:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12669:       fflush(ficlog);
                   12670:       goto end;
                   12671:     }
                   12672:       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  12673:     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  12674:     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  12675:     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  12676:   }
1.203     brouard  12677:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12678:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12679:   /* Third parameter line */
                   12680:   while(fgets(line, MAXLINE, ficpar)) {
                   12681:     /* If line starts with a # it is a comment */
                   12682:     if (line[0] == '#') {
                   12683:       numlinepar++;
1.283     brouard  12684:       printf("%s",line);
                   12685:       fprintf(ficres,"%s",line);
                   12686:       fprintf(ficparo,"%s",line);
                   12687:       fprintf(ficlog,"%s",line);
1.197     brouard  12688:       continue;
                   12689:     }else
                   12690:       break;
                   12691:   }
1.201     brouard  12692:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12693:     if (num_filled != 1){
1.302     brouard  12694:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12695:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12696:       model[0]='\0';
                   12697:       goto end;
                   12698:     }
                   12699:     else{
                   12700:       if (model[0]=='+'){
                   12701:        for(i=1; i<=strlen(model);i++)
                   12702:          modeltemp[i-1]=model[i];
1.201     brouard  12703:        strcpy(model,modeltemp); 
1.197     brouard  12704:       }
                   12705:     }
1.338     brouard  12706:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12707:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12708:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12709:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12710:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12711:   }
                   12712:   /* 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); */
                   12713:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12714:   /* 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  12715:   /* 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); */
                   12716:   /* 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  12717:   fflush(ficlog);
1.190     brouard  12718:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12719:   if(model[0]=='#'){
1.279     brouard  12720:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12721:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12722:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12723:     if(mle != -1){
1.279     brouard  12724:       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  12725:       exit(1);
                   12726:     }
                   12727:   }
1.126     brouard  12728:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12729:     ungetc(c,ficpar);
                   12730:     fgets(line, MAXLINE, ficpar);
                   12731:     numlinepar++;
1.195     brouard  12732:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12733:       z[0]=line[1];
1.342     brouard  12734:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  12735:       debugILK=1;printf("DebugILK\n");
1.195     brouard  12736:     }
                   12737:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12738:     fputs(line, stdout);
                   12739:     //puts(line);
1.126     brouard  12740:     fputs(line,ficparo);
                   12741:     fputs(line,ficlog);
                   12742:   }
                   12743:   ungetc(c,ficpar);
                   12744: 
                   12745:    
1.290     brouard  12746:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12747:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12748:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  12749:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   12750:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12751:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12752:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12753:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12754:   */
                   12755:   if (strlen(model)>1) 
1.187     brouard  12756:     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  12757:   else
1.187     brouard  12758:     ncovmodel=2; /* Constant and age */
1.133     brouard  12759:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12760:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12761:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12762:     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);
                   12763:     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);
                   12764:     fflush(stdout);
                   12765:     fclose (ficlog);
                   12766:     goto end;
                   12767:   }
1.126     brouard  12768:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12769:   delti=delti3[1][1];
                   12770:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12771:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12772: /* We could also provide initial parameters values giving by simple logistic regression 
                   12773:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12774:       /* for(i=1;i<nlstate;i++){ */
                   12775:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12776:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12777:       /* } */
1.126     brouard  12778:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12779:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12780:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12781:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12782:     fclose (ficparo);
                   12783:     fclose (ficlog);
                   12784:     goto end;
                   12785:     exit(0);
1.220     brouard  12786:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12787:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12788:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12789:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12790:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12791:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12792:     hess=matrix(1,npar,1,npar);
1.220     brouard  12793:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12794:     /* Read guessed parameters */
1.126     brouard  12795:     /* Reads comments: lines beginning with '#' */
                   12796:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12797:       ungetc(c,ficpar);
                   12798:       fgets(line, MAXLINE, ficpar);
                   12799:       numlinepar++;
1.141     brouard  12800:       fputs(line,stdout);
1.126     brouard  12801:       fputs(line,ficparo);
                   12802:       fputs(line,ficlog);
                   12803:     }
                   12804:     ungetc(c,ficpar);
                   12805:     
                   12806:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12807:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12808:     for(i=1; i <=nlstate; i++){
1.234     brouard  12809:       j=0;
1.126     brouard  12810:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12811:        if(jj==i) continue;
                   12812:        j++;
1.292     brouard  12813:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12814:          ungetc(c,ficpar);
                   12815:          fgets(line, MAXLINE, ficpar);
                   12816:          numlinepar++;
                   12817:          fputs(line,stdout);
                   12818:          fputs(line,ficparo);
                   12819:          fputs(line,ficlog);
                   12820:        }
                   12821:        ungetc(c,ficpar);
1.234     brouard  12822:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12823:        if ((i1 != i) || (j1 != jj)){
                   12824:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12825: It might be a problem of design; if ncovcol and the model are correct\n \
                   12826: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12827:          exit(1);
                   12828:        }
                   12829:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12830:        if(mle==1)
                   12831:          printf("%1d%1d",i,jj);
                   12832:        fprintf(ficlog,"%1d%1d",i,jj);
                   12833:        for(k=1; k<=ncovmodel;k++){
                   12834:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12835:          if(mle==1){
                   12836:            printf(" %lf",param[i][j][k]);
                   12837:            fprintf(ficlog," %lf",param[i][j][k]);
                   12838:          }
                   12839:          else
                   12840:            fprintf(ficlog," %lf",param[i][j][k]);
                   12841:          fprintf(ficparo," %lf",param[i][j][k]);
                   12842:        }
                   12843:        fscanf(ficpar,"\n");
                   12844:        numlinepar++;
                   12845:        if(mle==1)
                   12846:          printf("\n");
                   12847:        fprintf(ficlog,"\n");
                   12848:        fprintf(ficparo,"\n");
1.126     brouard  12849:       }
                   12850:     }  
                   12851:     fflush(ficlog);
1.234     brouard  12852:     
1.251     brouard  12853:     /* Reads parameters values */
1.126     brouard  12854:     p=param[1][1];
1.251     brouard  12855:     pstart=paramstart[1][1];
1.126     brouard  12856:     
                   12857:     /* Reads comments: lines beginning with '#' */
                   12858:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12859:       ungetc(c,ficpar);
                   12860:       fgets(line, MAXLINE, ficpar);
                   12861:       numlinepar++;
1.141     brouard  12862:       fputs(line,stdout);
1.126     brouard  12863:       fputs(line,ficparo);
                   12864:       fputs(line,ficlog);
                   12865:     }
                   12866:     ungetc(c,ficpar);
                   12867: 
                   12868:     for(i=1; i <=nlstate; i++){
                   12869:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12870:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12871:        if ( (i1-i) * (j1-j) != 0){
                   12872:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12873:          exit(1);
                   12874:        }
                   12875:        printf("%1d%1d",i,j);
                   12876:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12877:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12878:        for(k=1; k<=ncovmodel;k++){
                   12879:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12880:          printf(" %le",delti3[i][j][k]);
                   12881:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12882:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12883:        }
                   12884:        fscanf(ficpar,"\n");
                   12885:        numlinepar++;
                   12886:        printf("\n");
                   12887:        fprintf(ficparo,"\n");
                   12888:        fprintf(ficlog,"\n");
1.126     brouard  12889:       }
                   12890:     }
                   12891:     fflush(ficlog);
1.234     brouard  12892:     
1.145     brouard  12893:     /* Reads covariance matrix */
1.126     brouard  12894:     delti=delti3[1][1];
1.220     brouard  12895:                
                   12896:                
1.126     brouard  12897:     /* 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  12898:                
1.126     brouard  12899:     /* Reads comments: lines beginning with '#' */
                   12900:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12901:       ungetc(c,ficpar);
                   12902:       fgets(line, MAXLINE, ficpar);
                   12903:       numlinepar++;
1.141     brouard  12904:       fputs(line,stdout);
1.126     brouard  12905:       fputs(line,ficparo);
                   12906:       fputs(line,ficlog);
                   12907:     }
                   12908:     ungetc(c,ficpar);
1.220     brouard  12909:                
1.126     brouard  12910:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12911:     hess=matrix(1,npar,1,npar);
1.131     brouard  12912:     for(i=1; i <=npar; i++)
                   12913:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12914:                
1.194     brouard  12915:     /* Scans npar lines */
1.126     brouard  12916:     for(i=1; i <=npar; i++){
1.226     brouard  12917:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12918:       if(count != 3){
1.226     brouard  12919:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12920: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12921: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12922:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12923: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12924: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12925:        exit(1);
1.220     brouard  12926:       }else{
1.226     brouard  12927:        if(mle==1)
                   12928:          printf("%1d%1d%d",i1,j1,jk);
                   12929:       }
                   12930:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12931:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12932:       for(j=1; j <=i; j++){
1.226     brouard  12933:        fscanf(ficpar," %le",&matcov[i][j]);
                   12934:        if(mle==1){
                   12935:          printf(" %.5le",matcov[i][j]);
                   12936:        }
                   12937:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12938:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12939:       }
                   12940:       fscanf(ficpar,"\n");
                   12941:       numlinepar++;
                   12942:       if(mle==1)
1.220     brouard  12943:                                printf("\n");
1.126     brouard  12944:       fprintf(ficlog,"\n");
                   12945:       fprintf(ficparo,"\n");
                   12946:     }
1.194     brouard  12947:     /* End of read covariance matrix npar lines */
1.126     brouard  12948:     for(i=1; i <=npar; i++)
                   12949:       for(j=i+1;j<=npar;j++)
1.226     brouard  12950:        matcov[i][j]=matcov[j][i];
1.126     brouard  12951:     
                   12952:     if(mle==1)
                   12953:       printf("\n");
                   12954:     fprintf(ficlog,"\n");
                   12955:     
                   12956:     fflush(ficlog);
                   12957:     
                   12958:   }    /* End of mle != -3 */
1.218     brouard  12959:   
1.186     brouard  12960:   /*  Main data
                   12961:    */
1.290     brouard  12962:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12963:   /* num=lvector(1,n); */
                   12964:   /* moisnais=vector(1,n); */
                   12965:   /* annais=vector(1,n); */
                   12966:   /* moisdc=vector(1,n); */
                   12967:   /* andc=vector(1,n); */
                   12968:   /* weight=vector(1,n); */
                   12969:   /* agedc=vector(1,n); */
                   12970:   /* cod=ivector(1,n); */
                   12971:   /* for(i=1;i<=n;i++){ */
                   12972:   num=lvector(firstobs,lastobs);
                   12973:   moisnais=vector(firstobs,lastobs);
                   12974:   annais=vector(firstobs,lastobs);
                   12975:   moisdc=vector(firstobs,lastobs);
                   12976:   andc=vector(firstobs,lastobs);
                   12977:   weight=vector(firstobs,lastobs);
                   12978:   agedc=vector(firstobs,lastobs);
                   12979:   cod=ivector(firstobs,lastobs);
                   12980:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12981:     num[i]=0;
                   12982:     moisnais[i]=0;
                   12983:     annais[i]=0;
                   12984:     moisdc[i]=0;
                   12985:     andc[i]=0;
                   12986:     agedc[i]=0;
                   12987:     cod[i]=0;
                   12988:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12989:   }
1.290     brouard  12990:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12991:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12992:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12993:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12994:   tab=ivector(1,NCOVMAX);
1.144     brouard  12995:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12996:   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  12997: 
1.136     brouard  12998:   /* Reads data from file datafile */
                   12999:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13000:     goto end;
                   13001: 
                   13002:   /* Calculation of the number of parameters from char model */
1.234     brouard  13003:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13004:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13005:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13006:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13007:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13008:   */
                   13009:   
                   13010:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13011:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13012:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13013:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13014:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13015:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13016:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13017:   TvarF=ivector(1,NCOVMAX); /*  */
                   13018:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13019:   TvarV=ivector(1,NCOVMAX); /*  */
                   13020:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13021:   TvarA=ivector(1,NCOVMAX); /*  */
                   13022:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13023:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13024:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13025:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13026:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13027:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13028:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13029:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13030:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13031:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13032:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13033: 
1.230     brouard  13034:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13035:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13036:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13037:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13038:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  13039:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13040:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13041:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13042:   */
                   13043:   /* For model-covariate k tells which data-covariate to use but
                   13044:     because this model-covariate is a construction we invent a new column
                   13045:     ncovcol + k1
                   13046:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13047:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13048:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13049:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13050:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13051:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13052:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13053:   */
1.145     brouard  13054:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13055:   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  13056:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13057:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  13058:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  13059:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13060:                         4 covariates (3 plus signs)
                   13061:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13062:                           */  
                   13063:   for(i=1;i<NCOVMAX;i++)
                   13064:     Tage[i]=0;
1.230     brouard  13065:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13066:                                * individual dummy, fixed or varying:
                   13067:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13068:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13069:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13070:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13071:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13072:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13073:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13074:                                * individual quantitative, fixed or varying:
                   13075:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13076:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13077:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  13078: /* Main decodemodel */
                   13079: 
1.187     brouard  13080: 
1.223     brouard  13081:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13082:     goto end;
                   13083: 
1.137     brouard  13084:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13085:     nbwarn++;
                   13086:     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); 
                   13087:     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); 
                   13088:   }
1.136     brouard  13089:     /*  if(mle==1){*/
1.137     brouard  13090:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13091:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13092:   }
                   13093: 
                   13094:     /*-calculation of age at interview from date of interview and age at death -*/
                   13095:   agev=matrix(1,maxwav,1,imx);
                   13096: 
                   13097:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13098:     goto end;
                   13099: 
1.126     brouard  13100: 
1.136     brouard  13101:   agegomp=(int)agemin;
1.290     brouard  13102:   free_vector(moisnais,firstobs,lastobs);
                   13103:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13104:   /* free_matrix(mint,1,maxwav,1,n);
                   13105:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13106:   /* free_vector(moisdc,1,n); */
                   13107:   /* free_vector(andc,1,n); */
1.145     brouard  13108:   /* */
                   13109:   
1.126     brouard  13110:   wav=ivector(1,imx);
1.214     brouard  13111:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13112:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13113:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13114:   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.*/
                   13115:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13116:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13117:    
                   13118:   /* Concatenates waves */
1.214     brouard  13119:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13120:      Death is a valid wave (if date is known).
                   13121:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13122:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13123:      and mw[mi+1][i]. dh depends on stepm.
                   13124:   */
                   13125: 
1.126     brouard  13126:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13127:   /* Concatenates waves */
1.145     brouard  13128:  
1.290     brouard  13129:   free_vector(moisdc,firstobs,lastobs);
                   13130:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13131: 
1.126     brouard  13132:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13133:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13134:   ncodemax[1]=1;
1.145     brouard  13135:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13136:   cptcoveff=0;
1.220     brouard  13137:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13138:     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  13139:   }
                   13140:   
                   13141:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13142:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13143:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13144:     invalidvarcomb[i]=0;
                   13145:   
1.211     brouard  13146:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13147:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13148:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13149:   
1.200     brouard  13150:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13151:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13152:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13153:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13154:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13155:    * (currently 0 or 1) in the data.
                   13156:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13157:    * corresponding modality (h,j).
                   13158:    */
                   13159: 
1.145     brouard  13160:   h=0;
                   13161:   /*if (cptcovn > 0) */
1.126     brouard  13162:   m=pow(2,cptcoveff);
                   13163:  
1.144     brouard  13164:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13165:           * For k=4 covariates, h goes from 1 to m=2**k
                   13166:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13167:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13168:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13169:           *______________________________   *______________________
                   13170:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13171:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13172:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13173:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13174:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13175:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13176:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13177:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13178:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13179:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13180:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13181:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13182:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13183:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13184:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13185:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13186:           */                                     
1.212     brouard  13187:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13188:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13189:      * and the value of each covariate?
                   13190:      * V1=1, V2=1, V3=2, V4=1 ?
                   13191:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13192:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13193:      * In order to get the real value in the data, we use nbcode
                   13194:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13195:      * We are keeping this crazy system in order to be able (in the future?) 
                   13196:      * to have more than 2 values (0 or 1) for a covariate.
                   13197:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13198:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13199:      *              bbbbbbbb
                   13200:      *              76543210     
                   13201:      *   h-1        00000101 (6-1=5)
1.219     brouard  13202:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13203:      *           &
                   13204:      *     1        00000001 (1)
1.219     brouard  13205:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13206:      *          +1= 00000001 =1 
1.211     brouard  13207:      *
                   13208:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13209:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13210:      *    >>k'            11
                   13211:      *          &   00000001
                   13212:      *            = 00000001
                   13213:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13214:      * Reverse h=6 and m=16?
                   13215:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13216:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13217:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13218:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13219:      * V3=decodtabm(14,3,2**4)=2
                   13220:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13221:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13222:      *          &1 000000001
                   13223:      *           = 000000001
                   13224:      *         +1= 000000010 =2
                   13225:      *                  2211
                   13226:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13227:      *                  V3=2
1.220     brouard  13228:                 * codtabm and decodtabm are identical
1.211     brouard  13229:      */
                   13230: 
1.145     brouard  13231: 
                   13232:  free_ivector(Ndum,-1,NCOVMAX);
                   13233: 
                   13234: 
1.126     brouard  13235:     
1.186     brouard  13236:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13237:   strcpy(optionfilegnuplot,optionfilefiname);
                   13238:   if(mle==-3)
1.201     brouard  13239:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13240:   strcat(optionfilegnuplot,".gp");
                   13241: 
                   13242:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13243:     printf("Problem with file %s",optionfilegnuplot);
                   13244:   }
                   13245:   else{
1.204     brouard  13246:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13247:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13248:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13249:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13250:   }
                   13251:   /*  fclose(ficgp);*/
1.186     brouard  13252: 
                   13253: 
                   13254:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13255: 
                   13256:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13257:   if(mle==-3)
1.201     brouard  13258:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13259:   strcat(optionfilehtm,".htm");
                   13260:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13261:     printf("Problem with %s \n",optionfilehtm);
                   13262:     exit(0);
1.126     brouard  13263:   }
                   13264: 
                   13265:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13266:   strcat(optionfilehtmcov,"-cov.htm");
                   13267:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13268:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13269:   }
                   13270:   else{
                   13271:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13272: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13273: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13274:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13275:   }
                   13276: 
1.335     brouard  13277:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13278: <title>IMaCh %s</title></head>\n\
                   13279:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13280: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13281: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13282: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13283: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13284:   
                   13285:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13286: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13287: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13288: 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  13289: \n\
                   13290: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13291:  <ul><li><h4>Parameter files</h4>\n\
                   13292:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13293:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13294:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13295:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13296:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13297:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13298:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13299:          fileres,fileres,\
                   13300:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13301:   fflush(fichtm);
                   13302: 
                   13303:   strcpy(pathr,path);
                   13304:   strcat(pathr,optionfilefiname);
1.184     brouard  13305: #ifdef WIN32
                   13306:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13307: #else
1.126     brouard  13308:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13309: #endif
                   13310:          
1.126     brouard  13311:   
1.220     brouard  13312:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13313:                 and for any valid combination of covariates
1.126     brouard  13314:      and prints on file fileres'p'. */
1.251     brouard  13315:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13316:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13317: 
                   13318:   fprintf(fichtm,"\n");
1.286     brouard  13319:   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  13320:          ftol, stepm);
                   13321:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13322:   ncurrv=1;
                   13323:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13324:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13325:   ncurrv=i;
                   13326:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13327:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13328:   ncurrv=i;
                   13329:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13330:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13331:   ncurrv=i;
                   13332:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13333:   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", \
                   13334:           nlstate, ndeath, maxwav, mle, weightopt);
                   13335: 
                   13336:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13337: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13338: 
                   13339:   
1.317     brouard  13340:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13341: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13342: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13343:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13344:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13345:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13346:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13347:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13348:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13349: 
1.126     brouard  13350:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13351:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13352:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13353: 
                   13354:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13355:   /* For mortality only */
1.126     brouard  13356:   if (mle==-3){
1.136     brouard  13357:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13358:     for(i=1;i<=NDIM;i++)
                   13359:       for(j=1;j<=NDIM;j++)
                   13360:        ximort[i][j]=0.;
1.186     brouard  13361:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13362:     cens=ivector(firstobs,lastobs);
                   13363:     ageexmed=vector(firstobs,lastobs);
                   13364:     agecens=vector(firstobs,lastobs);
                   13365:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13366:                
1.126     brouard  13367:     for (i=1; i<=imx; i++){
                   13368:       dcwave[i]=-1;
                   13369:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13370:        if (s[m][i]>nlstate) {
                   13371:          dcwave[i]=m;
                   13372:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13373:          break;
                   13374:        }
1.126     brouard  13375:     }
1.226     brouard  13376:     
1.126     brouard  13377:     for (i=1; i<=imx; i++) {
                   13378:       if (wav[i]>0){
1.226     brouard  13379:        ageexmed[i]=agev[mw[1][i]][i];
                   13380:        j=wav[i];
                   13381:        agecens[i]=1.; 
                   13382:        
                   13383:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13384:          agecens[i]=agev[mw[j][i]][i];
                   13385:          cens[i]= 1;
                   13386:        }else if (ageexmed[i]< 1) 
                   13387:          cens[i]= -1;
                   13388:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13389:          cens[i]=0 ;
1.126     brouard  13390:       }
                   13391:       else cens[i]=-1;
                   13392:     }
                   13393:     
                   13394:     for (i=1;i<=NDIM;i++) {
                   13395:       for (j=1;j<=NDIM;j++)
1.226     brouard  13396:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13397:     }
                   13398:     
1.302     brouard  13399:     p[1]=0.0268; p[NDIM]=0.083;
                   13400:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13401:     
                   13402:     
1.136     brouard  13403: #ifdef GSL
                   13404:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13405: #else
1.126     brouard  13406:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13407: #endif
1.201     brouard  13408:     strcpy(filerespow,"POW-MORT_"); 
                   13409:     strcat(filerespow,fileresu);
1.126     brouard  13410:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13411:       printf("Problem with resultfile: %s\n", filerespow);
                   13412:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13413:     }
1.136     brouard  13414: #ifdef GSL
                   13415:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13416: #else
1.126     brouard  13417:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13418: #endif
1.126     brouard  13419:     /*  for (i=1;i<=nlstate;i++)
                   13420:        for(j=1;j<=nlstate+ndeath;j++)
                   13421:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13422:     */
                   13423:     fprintf(ficrespow,"\n");
1.136     brouard  13424: #ifdef GSL
                   13425:     /* gsl starts here */ 
                   13426:     T = gsl_multimin_fminimizer_nmsimplex;
                   13427:     gsl_multimin_fminimizer *sfm = NULL;
                   13428:     gsl_vector *ss, *x;
                   13429:     gsl_multimin_function minex_func;
                   13430: 
                   13431:     /* Initial vertex size vector */
                   13432:     ss = gsl_vector_alloc (NDIM);
                   13433:     
                   13434:     if (ss == NULL){
                   13435:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13436:     }
                   13437:     /* Set all step sizes to 1 */
                   13438:     gsl_vector_set_all (ss, 0.001);
                   13439: 
                   13440:     /* Starting point */
1.126     brouard  13441:     
1.136     brouard  13442:     x = gsl_vector_alloc (NDIM);
                   13443:     
                   13444:     if (x == NULL){
                   13445:       gsl_vector_free(ss);
                   13446:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13447:     }
                   13448:   
                   13449:     /* Initialize method and iterate */
                   13450:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13451:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13452:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13453:     gsl_vector_set(x, 0, p[1]);
                   13454:     gsl_vector_set(x, 1, p[2]);
                   13455: 
                   13456:     minex_func.f = &gompertz_f;
                   13457:     minex_func.n = NDIM;
                   13458:     minex_func.params = (void *)&p; /* ??? */
                   13459:     
                   13460:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13461:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13462:     
                   13463:     printf("Iterations beginning .....\n\n");
                   13464:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13465: 
                   13466:     iteri=0;
                   13467:     while (rval == GSL_CONTINUE){
                   13468:       iteri++;
                   13469:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13470:       
                   13471:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13472:       fflush(0);
                   13473:       
                   13474:       if (status) 
                   13475:         break;
                   13476:       
                   13477:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13478:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13479:       
                   13480:       if (rval == GSL_SUCCESS)
                   13481:         printf ("converged to a local maximum at\n");
                   13482:       
                   13483:       printf("%5d ", iteri);
                   13484:       for (it = 0; it < NDIM; it++){
                   13485:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13486:       }
                   13487:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13488:     }
                   13489:     
                   13490:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13491:     
                   13492:     gsl_vector_free(x); /* initial values */
                   13493:     gsl_vector_free(ss); /* inital step size */
                   13494:     for (it=0; it<NDIM; it++){
                   13495:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13496:       fprintf(ficrespow," %.12lf", p[it]);
                   13497:     }
                   13498:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13499: #endif
                   13500: #ifdef POWELL
                   13501:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13502: #endif  
1.126     brouard  13503:     fclose(ficrespow);
                   13504:     
1.203     brouard  13505:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13506: 
                   13507:     for(i=1; i <=NDIM; i++)
                   13508:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13509:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13510:     
                   13511:     printf("\nCovariance matrix\n ");
1.203     brouard  13512:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13513:     for(i=1; i <=NDIM; i++) {
                   13514:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13515:                                printf("%f ",matcov[i][j]);
                   13516:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13517:       }
1.203     brouard  13518:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13519:     }
                   13520:     
                   13521:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13522:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13523:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13524:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13525:     }
1.302     brouard  13526:     lsurv=vector(agegomp,AGESUP);
                   13527:     lpop=vector(agegomp,AGESUP);
                   13528:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13529:     lsurv[agegomp]=100000;
                   13530:     
                   13531:     for (k=agegomp;k<=AGESUP;k++) {
                   13532:       agemortsup=k;
                   13533:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13534:     }
                   13535:     
                   13536:     for (k=agegomp;k<agemortsup;k++)
                   13537:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13538:     
                   13539:     for (k=agegomp;k<agemortsup;k++){
                   13540:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13541:       sumlpop=sumlpop+lpop[k];
                   13542:     }
                   13543:     
                   13544:     tpop[agegomp]=sumlpop;
                   13545:     for (k=agegomp;k<(agemortsup-3);k++){
                   13546:       /*  tpop[k+1]=2;*/
                   13547:       tpop[k+1]=tpop[k]-lpop[k];
                   13548:     }
                   13549:     
                   13550:     
                   13551:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13552:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13553:       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]);
                   13554:     
                   13555:     
                   13556:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13557:                ageminpar=50;
                   13558:                agemaxpar=100;
1.194     brouard  13559:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13560:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13561: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13562: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13563:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13564: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13565: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13566:     }else{
                   13567:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13568:                        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  13569:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13570:                }
1.201     brouard  13571:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13572:                     stepm, weightopt,\
                   13573:                     model,imx,p,matcov,agemortsup);
                   13574:     
1.302     brouard  13575:     free_vector(lsurv,agegomp,AGESUP);
                   13576:     free_vector(lpop,agegomp,AGESUP);
                   13577:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13578:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13579:     free_ivector(dcwave,firstobs,lastobs);
                   13580:     free_vector(agecens,firstobs,lastobs);
                   13581:     free_vector(ageexmed,firstobs,lastobs);
                   13582:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13583: #ifdef GSL
1.136     brouard  13584: #endif
1.186     brouard  13585:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13586:   /* Standard  */
                   13587:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13588:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13589:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13590:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13591:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13592:     for (k=1; k<=npar;k++)
                   13593:       printf(" %d %8.5f",k,p[k]);
                   13594:     printf("\n");
1.205     brouard  13595:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13596:       /* mlikeli uses func not funcone */
1.247     brouard  13597:       /* for(i=1;i<nlstate;i++){ */
                   13598:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13599:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13600:       /* } */
1.205     brouard  13601:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13602:     }
                   13603:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13604:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13605:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13606:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13607:     }
                   13608:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13609:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13610:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13611:           /* exit(0); */
1.126     brouard  13612:     for (k=1; k<=npar;k++)
                   13613:       printf(" %d %8.5f",k,p[k]);
                   13614:     printf("\n");
                   13615:     
                   13616:     /*--------- results files --------------*/
1.283     brouard  13617:     /* 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  13618:     
                   13619:     
                   13620:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13621:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13622:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13623: 
                   13624:     printf("#model=  1      +     age ");
                   13625:     fprintf(ficres,"#model=  1      +     age ");
                   13626:     fprintf(ficlog,"#model=  1      +     age ");
                   13627:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13628: </ul>", model);
                   13629: 
                   13630:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13631:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13632:     if(nagesqr==1){
                   13633:       printf("  + age*age  ");
                   13634:       fprintf(ficres,"  + age*age  ");
                   13635:       fprintf(ficlog,"  + age*age  ");
                   13636:       fprintf(fichtm, "<th>+ age*age</th>");
                   13637:     }
                   13638:     for(j=1;j <=ncovmodel-2;j++){
                   13639:       if(Typevar[j]==0) {
                   13640:        printf("  +      V%d  ",Tvar[j]);
                   13641:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13642:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13643:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13644:       }else if(Typevar[j]==1) {
                   13645:        printf("  +    V%d*age ",Tvar[j]);
                   13646:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13647:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13648:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13649:       }else if(Typevar[j]==2) {
                   13650:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13651:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13652:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13653:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13654:       }
                   13655:     }
                   13656:     printf("\n");
                   13657:     fprintf(ficres,"\n");
                   13658:     fprintf(ficlog,"\n");
                   13659:     fprintf(fichtm, "</tr>");
                   13660:     fprintf(fichtm, "\n");
                   13661:     
                   13662:     
1.126     brouard  13663:     for(i=1,jk=1; i <=nlstate; i++){
                   13664:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13665:        if (k != i) {
1.319     brouard  13666:          fprintf(fichtm, "<tr>");
1.225     brouard  13667:          printf("%d%d ",i,k);
                   13668:          fprintf(ficlog,"%d%d ",i,k);
                   13669:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13670:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13671:          for(j=1; j <=ncovmodel; j++){
                   13672:            printf("%12.7f ",p[jk]);
                   13673:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13674:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13675:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13676:            jk++; 
                   13677:          }
                   13678:          printf("\n");
                   13679:          fprintf(ficlog,"\n");
                   13680:          fprintf(ficres,"\n");
1.319     brouard  13681:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13682:        }
1.126     brouard  13683:       }
                   13684:     }
1.319     brouard  13685:     /* fprintf(fichtm,"</tr>\n"); */
                   13686:     fprintf(fichtm,"</table>\n");
                   13687:     fprintf(fichtm, "\n");
                   13688: 
1.203     brouard  13689:     if(mle != 0){
                   13690:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13691:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13692:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13693:       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");
                   13694:       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  13695:       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  13696:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13697:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13698:       if(nagesqr==1){
                   13699:        printf("  + age*age  ");
                   13700:        fprintf(ficres,"  + age*age  ");
                   13701:        fprintf(ficlog,"  + age*age  ");
                   13702:        fprintf(fichtm, "<th>+ age*age</th>");
                   13703:       }
                   13704:       for(j=1;j <=ncovmodel-2;j++){
                   13705:        if(Typevar[j]==0) {
                   13706:          printf("  +      V%d  ",Tvar[j]);
                   13707:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13708:        }else if(Typevar[j]==1) {
                   13709:          printf("  +    V%d*age ",Tvar[j]);
                   13710:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13711:        }else if(Typevar[j]==2) {
                   13712:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13713:        }
                   13714:       }
                   13715:       fprintf(fichtm, "</tr>\n");
                   13716:  
1.203     brouard  13717:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13718:        for(k=1; k <=(nlstate+ndeath); k++){
                   13719:          if (k != i) {
1.319     brouard  13720:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13721:            printf("%d%d ",i,k);
                   13722:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13723:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13724:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13725:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13726:              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]));
                   13727:              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  13728:              if(fabs(wald) > 1.96){
1.321     brouard  13729:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13730:              }else{
                   13731:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13732:              }
1.324     brouard  13733:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13734:              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  13735:              jk++; 
                   13736:            }
                   13737:            printf("\n");
                   13738:            fprintf(ficlog,"\n");
1.319     brouard  13739:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13740:          }
                   13741:        }
1.193     brouard  13742:       }
1.203     brouard  13743:     } /* end of hesscov and Wald tests */
1.319     brouard  13744:     fprintf(fichtm,"</table>\n");
1.225     brouard  13745:     
1.203     brouard  13746:     /*  */
1.126     brouard  13747:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13748:     printf("# Scales (for hessian or gradient estimation)\n");
                   13749:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13750:     for(i=1,jk=1; i <=nlstate; i++){
                   13751:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13752:        if (j!=i) {
                   13753:          fprintf(ficres,"%1d%1d",i,j);
                   13754:          printf("%1d%1d",i,j);
                   13755:          fprintf(ficlog,"%1d%1d",i,j);
                   13756:          for(k=1; k<=ncovmodel;k++){
                   13757:            printf(" %.5e",delti[jk]);
                   13758:            fprintf(ficlog," %.5e",delti[jk]);
                   13759:            fprintf(ficres," %.5e",delti[jk]);
                   13760:            jk++;
                   13761:          }
                   13762:          printf("\n");
                   13763:          fprintf(ficlog,"\n");
                   13764:          fprintf(ficres,"\n");
                   13765:        }
1.126     brouard  13766:       }
                   13767:     }
                   13768:     
                   13769:     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.203     brouard  13770:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13771:       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");
                   13772:     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");
                   13773:     /* # 121 Var(a12)\n\ */
                   13774:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13775:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13776:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13777:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13778:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13779:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13780:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13781:     
                   13782:     
                   13783:     /* Just to have a covariance matrix which will be more understandable
                   13784:        even is we still don't want to manage dictionary of variables
                   13785:     */
                   13786:     for(itimes=1;itimes<=2;itimes++){
                   13787:       jj=0;
                   13788:       for(i=1; i <=nlstate; i++){
1.225     brouard  13789:        for(j=1; j <=nlstate+ndeath; j++){
                   13790:          if(j==i) continue;
                   13791:          for(k=1; k<=ncovmodel;k++){
                   13792:            jj++;
                   13793:            ca[0]= k+'a'-1;ca[1]='\0';
                   13794:            if(itimes==1){
                   13795:              if(mle>=1)
                   13796:                printf("#%1d%1d%d",i,j,k);
                   13797:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13798:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13799:            }else{
                   13800:              if(mle>=1)
                   13801:                printf("%1d%1d%d",i,j,k);
                   13802:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13803:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13804:            }
                   13805:            ll=0;
                   13806:            for(li=1;li <=nlstate; li++){
                   13807:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13808:                if(lj==li) continue;
                   13809:                for(lk=1;lk<=ncovmodel;lk++){
                   13810:                  ll++;
                   13811:                  if(ll<=jj){
                   13812:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13813:                    if(ll<jj){
                   13814:                      if(itimes==1){
                   13815:                        if(mle>=1)
                   13816:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13817:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13818:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13819:                      }else{
                   13820:                        if(mle>=1)
                   13821:                          printf(" %.5e",matcov[jj][ll]); 
                   13822:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13823:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13824:                      }
                   13825:                    }else{
                   13826:                      if(itimes==1){
                   13827:                        if(mle>=1)
                   13828:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13829:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13830:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13831:                      }else{
                   13832:                        if(mle>=1)
                   13833:                          printf(" %.7e",matcov[jj][ll]); 
                   13834:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13835:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13836:                      }
                   13837:                    }
                   13838:                  }
                   13839:                } /* end lk */
                   13840:              } /* end lj */
                   13841:            } /* end li */
                   13842:            if(mle>=1)
                   13843:              printf("\n");
                   13844:            fprintf(ficlog,"\n");
                   13845:            fprintf(ficres,"\n");
                   13846:            numlinepar++;
                   13847:          } /* end k*/
                   13848:        } /*end j */
1.126     brouard  13849:       } /* end i */
                   13850:     } /* end itimes */
                   13851:     
                   13852:     fflush(ficlog);
                   13853:     fflush(ficres);
1.225     brouard  13854:     while(fgets(line, MAXLINE, ficpar)) {
                   13855:       /* If line starts with a # it is a comment */
                   13856:       if (line[0] == '#') {
                   13857:        numlinepar++;
                   13858:        fputs(line,stdout);
                   13859:        fputs(line,ficparo);
                   13860:        fputs(line,ficlog);
1.299     brouard  13861:        fputs(line,ficres);
1.225     brouard  13862:        continue;
                   13863:       }else
                   13864:        break;
                   13865:     }
                   13866:     
1.209     brouard  13867:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13868:     /*   ungetc(c,ficpar); */
                   13869:     /*   fgets(line, MAXLINE, ficpar); */
                   13870:     /*   fputs(line,stdout); */
                   13871:     /*   fputs(line,ficparo); */
                   13872:     /* } */
                   13873:     /* ungetc(c,ficpar); */
1.126     brouard  13874:     
                   13875:     estepm=0;
1.209     brouard  13876:     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  13877:       
                   13878:       if (num_filled != 6) {
                   13879:        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);
                   13880:        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);
                   13881:        goto end;
                   13882:       }
                   13883:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13884:     }
                   13885:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13886:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13887:     
1.209     brouard  13888:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13889:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13890:     if (fage <= 2) {
                   13891:       bage = ageminpar;
                   13892:       fage = agemaxpar;
                   13893:     }
                   13894:     
                   13895:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13896:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13897:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13898:                
1.186     brouard  13899:     /* Other stuffs, more or less useful */    
1.254     brouard  13900:     while(fgets(line, MAXLINE, ficpar)) {
                   13901:       /* If line starts with a # it is a comment */
                   13902:       if (line[0] == '#') {
                   13903:        numlinepar++;
                   13904:        fputs(line,stdout);
                   13905:        fputs(line,ficparo);
                   13906:        fputs(line,ficlog);
1.299     brouard  13907:        fputs(line,ficres);
1.254     brouard  13908:        continue;
                   13909:       }else
                   13910:        break;
                   13911:     }
                   13912: 
                   13913:     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){
                   13914:       
                   13915:       if (num_filled != 7) {
                   13916:        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);
                   13917:        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);
                   13918:        goto end;
                   13919:       }
                   13920:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13921:       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);
                   13922:       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);
                   13923:       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  13924:     }
1.254     brouard  13925: 
                   13926:     while(fgets(line, MAXLINE, ficpar)) {
                   13927:       /* If line starts with a # it is a comment */
                   13928:       if (line[0] == '#') {
                   13929:        numlinepar++;
                   13930:        fputs(line,stdout);
                   13931:        fputs(line,ficparo);
                   13932:        fputs(line,ficlog);
1.299     brouard  13933:        fputs(line,ficres);
1.254     brouard  13934:        continue;
                   13935:       }else
                   13936:        break;
1.126     brouard  13937:     }
                   13938:     
                   13939:     
                   13940:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13941:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13942:     
1.254     brouard  13943:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13944:       if (num_filled != 1) {
                   13945:        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);
                   13946:        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);
                   13947:        goto end;
                   13948:       }
                   13949:       printf("pop_based=%d\n",popbased);
                   13950:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13951:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13952:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13953:     }
                   13954:      
1.258     brouard  13955:     /* Results */
1.332     brouard  13956:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13957:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13958:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13959:     endishere=0;
1.258     brouard  13960:     nresult=0;
1.308     brouard  13961:     parameterline=0;
1.258     brouard  13962:     do{
                   13963:       if(!fgets(line, MAXLINE, ficpar)){
                   13964:        endishere=1;
1.308     brouard  13965:        parameterline=15;
1.258     brouard  13966:       }else if (line[0] == '#') {
                   13967:        /* If line starts with a # it is a comment */
1.254     brouard  13968:        numlinepar++;
                   13969:        fputs(line,stdout);
                   13970:        fputs(line,ficparo);
                   13971:        fputs(line,ficlog);
1.299     brouard  13972:        fputs(line,ficres);
1.254     brouard  13973:        continue;
1.258     brouard  13974:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13975:        parameterline=11;
1.296     brouard  13976:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13977:        parameterline=12;
1.307     brouard  13978:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13979:        parameterline=13;
1.307     brouard  13980:       }
1.258     brouard  13981:       else{
                   13982:        parameterline=14;
1.254     brouard  13983:       }
1.308     brouard  13984:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13985:       case 11:
1.296     brouard  13986:        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)){
                   13987:                  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  13988:          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);
                   13989:          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);
                   13990:          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);
                   13991:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13992:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13993:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13994:           prvforecast = 1;
                   13995:        } 
                   13996:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13997:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13998:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13999:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14000:           prvforecast = 2;
                   14001:        }
                   14002:        else {
                   14003:          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);
                   14004:          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);
                   14005:          goto end;
1.258     brouard  14006:        }
1.254     brouard  14007:        break;
1.258     brouard  14008:       case 12:
1.296     brouard  14009:        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)){
                   14010:           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);
                   14011:          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);
                   14012:          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);
                   14013:          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);
                   14014:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14015:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14016:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14017:           prvbackcast = 1;
                   14018:        } 
                   14019:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14020:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14021:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14022:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14023:           prvbackcast = 2;
                   14024:        }
                   14025:        else {
                   14026:          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);
                   14027:          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);
                   14028:          goto end;
1.258     brouard  14029:        }
1.230     brouard  14030:        break;
1.258     brouard  14031:       case 13:
1.332     brouard  14032:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14033:        nresult++; /* Sum of resultlines */
1.342     brouard  14034:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14035:        /* removefirstspace(&resultlineori); */
                   14036:        
                   14037:        if(strstr(resultlineori,"v") !=0){
                   14038:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14039:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14040:          return 1;
                   14041:        }
                   14042:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14043:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14044:        if(nresult > MAXRESULTLINESPONE-1){
                   14045:          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);
                   14046:          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  14047:          goto end;
                   14048:        }
1.332     brouard  14049:        
1.310     brouard  14050:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14051:          fprintf(ficparo,"result: %s\n",resultline);
                   14052:          fprintf(ficres,"result: %s\n",resultline);
                   14053:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14054:        } else
                   14055:          goto end;
1.307     brouard  14056:        break;
                   14057:       case 14:
                   14058:        printf("Error: Unknown command '%s'\n",line);
                   14059:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14060:        if(line[0] == ' ' || line[0] == '\n'){
                   14061:          printf("It should not be an empty line '%s'\n",line);
                   14062:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14063:        }         
1.307     brouard  14064:        if(ncovmodel >=2 && nresult==0 ){
                   14065:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14066:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14067:        }
1.307     brouard  14068:        /* goto end; */
                   14069:        break;
1.308     brouard  14070:       case 15:
                   14071:        printf("End of resultlines.\n");
                   14072:        fprintf(ficlog,"End of resultlines.\n");
                   14073:        break;
                   14074:       default: /* parameterline =0 */
1.307     brouard  14075:        nresult=1;
                   14076:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14077:       } /* End switch parameterline */
                   14078:     }while(endishere==0); /* End do */
1.126     brouard  14079:     
1.230     brouard  14080:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14081:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14082:     
                   14083:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14084:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14085:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14086: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14087: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14088:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14089: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14090: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14091:     }else{
1.270     brouard  14092:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14093:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14094:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14095:       if(prvforecast==1){
                   14096:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14097:         jprojd=jproj1;
                   14098:         mprojd=mproj1;
                   14099:         anprojd=anproj1;
                   14100:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14101:         jprojf=jproj2;
                   14102:         mprojf=mproj2;
                   14103:         anprojf=anproj2;
                   14104:       } else if(prvforecast == 2){
                   14105:         dateprojd=dateintmean;
                   14106:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14107:         dateprojf=dateintmean+yrfproj;
                   14108:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14109:       }
                   14110:       if(prvbackcast==1){
                   14111:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14112:         jbackd=jback1;
                   14113:         mbackd=mback1;
                   14114:         anbackd=anback1;
                   14115:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14116:         jbackf=jback2;
                   14117:         mbackf=mback2;
                   14118:         anbackf=anback2;
                   14119:       } else if(prvbackcast == 2){
                   14120:         datebackd=dateintmean;
                   14121:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14122:         datebackf=dateintmean-yrbproj;
                   14123:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14124:       }
                   14125:       
                   14126:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  14127:     }
                   14128:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14129:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14130:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14131:                
1.225     brouard  14132:     /*------------ free_vector  -------------*/
                   14133:     /*  chdir(path); */
1.220     brouard  14134:                
1.215     brouard  14135:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14136:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14137:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14138:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14139:     free_lvector(num,firstobs,lastobs);
                   14140:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14141:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14142:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14143:     fclose(ficparo);
                   14144:     fclose(ficres);
1.220     brouard  14145:                
                   14146:                
1.186     brouard  14147:     /* Other results (useful)*/
1.220     brouard  14148:                
                   14149:                
1.126     brouard  14150:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14151:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14152:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14153:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14154:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14155:     fclose(ficrespl);
                   14156: 
                   14157:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14158:     /*#include "hpijx.h"*/
1.332     brouard  14159:     /** 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?*/
                   14160:     /* calls hpxij with combination k */
1.180     brouard  14161:     hPijx(p, bage, fage);
1.145     brouard  14162:     fclose(ficrespij);
1.227     brouard  14163:     
1.220     brouard  14164:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14165:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14166:     k=1;
1.126     brouard  14167:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14168:     
1.269     brouard  14169:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14170:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14171:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14172:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14173:        for(k=1;k<=ncovcombmax;k++)
                   14174:          probs[i][j][k]=0.;
1.269     brouard  14175:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14176:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14177:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14178:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14179:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14180:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14181:          for(k=1;k<=ncovcombmax;k++)
                   14182:            mobaverages[i][j][k]=0.;
1.219     brouard  14183:       mobaverage=mobaverages;
                   14184:       if (mobilav!=0) {
1.235     brouard  14185:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14186:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14187:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14188:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14189:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14190:        }
1.269     brouard  14191:       } else if (mobilavproj !=0) {
1.235     brouard  14192:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14193:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14194:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14195:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14196:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14197:        }
1.269     brouard  14198:       }else{
                   14199:        printf("Internal error moving average\n");
                   14200:        fflush(stdout);
                   14201:        exit(1);
1.219     brouard  14202:       }
                   14203:     }/* end if moving average */
1.227     brouard  14204:     
1.126     brouard  14205:     /*---------- Forecasting ------------------*/
1.296     brouard  14206:     if(prevfcast==1){ 
                   14207:       /*   /\*    if(stepm ==1){*\/ */
                   14208:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14209:       /*This done previously after freqsummary.*/
                   14210:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14211:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14212:       
                   14213:       /* } else if (prvforecast==2){ */
                   14214:       /*   /\*    if(stepm ==1){*\/ */
                   14215:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14216:       /* } */
                   14217:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14218:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14219:     }
1.269     brouard  14220: 
1.296     brouard  14221:     /* Prevbcasting */
                   14222:     if(prevbcast==1){
1.219     brouard  14223:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14224:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14225:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14226: 
                   14227:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14228: 
                   14229:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14230: 
1.219     brouard  14231:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14232:       fclose(ficresplb);
                   14233: 
1.222     brouard  14234:       hBijx(p, bage, fage, mobaverage);
                   14235:       fclose(ficrespijb);
1.219     brouard  14236: 
1.296     brouard  14237:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14238:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14239:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14240:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14241:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14242:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14243: 
                   14244:       
1.269     brouard  14245:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14246: 
                   14247:       
1.269     brouard  14248:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14249:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14250:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14251:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14252:     }    /* end  Prevbcasting */
1.268     brouard  14253:  
1.186     brouard  14254:  
                   14255:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14256: 
1.215     brouard  14257:     free_ivector(wav,1,imx);
                   14258:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14259:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14260:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14261:                
                   14262:                
1.127     brouard  14263:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14264:                
1.201     brouard  14265:     strcpy(filerese,"E_");
                   14266:     strcat(filerese,fileresu);
1.126     brouard  14267:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14268:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14269:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14270:     }
1.208     brouard  14271:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14272:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14273: 
                   14274:     pstamp(ficreseij);
1.219     brouard  14275:                
1.235     brouard  14276:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14277:     if (cptcovn < 1){i1=1;}
                   14278:     
                   14279:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14280:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14281:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14282:        continue;
1.219     brouard  14283:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14284:       printf("\n#****** ");
1.225     brouard  14285:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14286:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14287:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14288:       }
                   14289:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14290:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14291:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14292:       }
                   14293:       fprintf(ficreseij,"******\n");
1.235     brouard  14294:       printf("******\n");
1.219     brouard  14295:       
                   14296:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14297:       oldm=oldms;savm=savms;
1.330     brouard  14298:       /* 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  14299:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14300:       
1.219     brouard  14301:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14302:     }
                   14303:     fclose(ficreseij);
1.208     brouard  14304:     printf("done evsij\n");fflush(stdout);
                   14305:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14306: 
1.218     brouard  14307:                
1.227     brouard  14308:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14309:     /* Should be moved in a function */                
1.201     brouard  14310:     strcpy(filerest,"T_");
                   14311:     strcat(filerest,fileresu);
1.127     brouard  14312:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14313:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14314:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14315:     }
1.208     brouard  14316:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14317:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14318:     strcpy(fileresstde,"STDE_");
                   14319:     strcat(fileresstde,fileresu);
1.126     brouard  14320:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14321:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14322:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14323:     }
1.227     brouard  14324:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14325:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14326: 
1.201     brouard  14327:     strcpy(filerescve,"CVE_");
                   14328:     strcat(filerescve,fileresu);
1.126     brouard  14329:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14330:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14331:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14332:     }
1.227     brouard  14333:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14334:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14335: 
1.201     brouard  14336:     strcpy(fileresv,"V_");
                   14337:     strcat(fileresv,fileresu);
1.126     brouard  14338:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14339:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14340:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14341:     }
1.227     brouard  14342:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14343:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14344: 
1.235     brouard  14345:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14346:     if (cptcovn < 1){i1=1;}
                   14347:     
1.334     brouard  14348:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14349:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14350:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14351:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14352:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14353:       /* */
                   14354:       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  14355:        continue;
1.321     brouard  14356:       printf("\n# model %s \n#****** Result for:", model);
                   14357:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14358:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14359:       /* It might not be a good idea to mix dummies and quantitative */
                   14360:       /* 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 *\/ */
                   14361:       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 */
                   14362:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14363:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14364:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14365:         * (V5 is quanti) V4 and V3 are dummies
                   14366:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14367:         *                                                              l=1 l=2
                   14368:         *                                                           k=1  1   1   0   0
                   14369:         *                                                           k=2  2   1   1   0
                   14370:         *                                                           k=3 [1] [2]  0   1
                   14371:         *                                                           k=4  2   2   1   1
                   14372:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14373:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14374:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14375:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14376:         */
                   14377:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14378:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14379: /* We give up with the combinations!! */
1.342     brouard  14380:        /* if(debugILK) */
                   14381:        /*   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  14382: 
                   14383:        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  14384:          /* 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] */
                   14385:          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  */
                   14386:          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  */
                   14387:          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  14388:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14389:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14390:          }else{
                   14391:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14392:          }
                   14393:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14394:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14395:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14396:          /* For each selected (single) quantitative value */
1.337     brouard  14397:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14398:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14399:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14400:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14401:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14402:          }else{
                   14403:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14404:          }
                   14405:        }else{
                   14406:          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 */
                   14407:          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 */
                   14408:          exit(1);
                   14409:        }
1.335     brouard  14410:       } /* End loop for each variable in the resultline */
1.334     brouard  14411:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14412:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14413:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14414:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14415:       /* }      */
1.208     brouard  14416:       fprintf(ficrest,"******\n");
1.227     brouard  14417:       fprintf(ficlog,"******\n");
                   14418:       printf("******\n");
1.208     brouard  14419:       
                   14420:       fprintf(ficresstdeij,"\n#****** ");
                   14421:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14422:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14423:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14424:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14425:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14426:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14427:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14428:       }
                   14429:       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  14430:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14431:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14432:       }        
1.208     brouard  14433:       fprintf(ficresstdeij,"******\n");
                   14434:       fprintf(ficrescveij,"******\n");
                   14435:       
                   14436:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14437:       /* pstamp(ficresvij); */
1.225     brouard  14438:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14439:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14440:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14441:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14442:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14443:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14444:       }        
1.208     brouard  14445:       fprintf(ficresvij,"******\n");
                   14446:       
                   14447:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14448:       oldm=oldms;savm=savms;
1.235     brouard  14449:       printf(" cvevsij ");
                   14450:       fprintf(ficlog, " cvevsij ");
                   14451:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14452:       printf(" end cvevsij \n ");
                   14453:       fprintf(ficlog, " end cvevsij \n ");
                   14454:       
                   14455:       /*
                   14456:        */
                   14457:       /* goto endfree; */
                   14458:       
                   14459:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14460:       pstamp(ficrest);
                   14461:       
1.269     brouard  14462:       epj=vector(1,nlstate+1);
1.208     brouard  14463:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14464:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14465:        cptcod= 0; /* To be deleted */
                   14466:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14467:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14468:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
1.227     brouard  14469:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
                   14470:        if(vpopbased==1)
                   14471:          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);
                   14472:        else
1.288     brouard  14473:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14474:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14475:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14476:        fprintf(ficrest,"\n");
                   14477:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14478:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14479:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14480:        for(age=bage; age <=fage ;age++){
1.235     brouard  14481:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14482:          if (vpopbased==1) {
                   14483:            if(mobilav ==0){
                   14484:              for(i=1; i<=nlstate;i++)
                   14485:                prlim[i][i]=probs[(int)age][i][k];
                   14486:            }else{ /* mobilav */ 
                   14487:              for(i=1; i<=nlstate;i++)
                   14488:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14489:            }
                   14490:          }
1.219     brouard  14491:          
1.227     brouard  14492:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14493:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14494:          /* printf(" age %4.0f ",age); */
                   14495:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14496:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14497:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14498:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14499:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14500:            }
                   14501:            epj[nlstate+1] +=epj[j];
                   14502:          }
                   14503:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14504:          
1.227     brouard  14505:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14506:            for(j=1;j <=nlstate;j++)
                   14507:              vepp += vareij[i][j][(int)age];
                   14508:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14509:          for(j=1;j <=nlstate;j++){
                   14510:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14511:          }
                   14512:          fprintf(ficrest,"\n");
                   14513:        }
1.208     brouard  14514:       } /* End vpopbased */
1.269     brouard  14515:       free_vector(epj,1,nlstate+1);
1.208     brouard  14516:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14517:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14518:       printf("done selection\n");fflush(stdout);
                   14519:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14520:       
1.335     brouard  14521:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14522: 
                   14523:     printf("done State-specific expectancies\n");fflush(stdout);
                   14524:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14525: 
1.335     brouard  14526:     /* variance-covariance of forward period prevalence */
1.269     brouard  14527:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14528: 
1.227     brouard  14529:     
1.290     brouard  14530:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14531:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14532:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14533:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14534:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14535:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14536:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14537:     free_ivector(tab,1,NCOVMAX);
                   14538:     fclose(ficresstdeij);
                   14539:     fclose(ficrescveij);
                   14540:     fclose(ficresvij);
                   14541:     fclose(ficrest);
                   14542:     fclose(ficpar);
                   14543:     
                   14544:     
1.126     brouard  14545:     /*---------- End : free ----------------*/
1.219     brouard  14546:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14547:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14548:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14549:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14550:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14551:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14552:   /* endfree:*/
                   14553:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14554:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14555:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  14556:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   14557:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14558:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14559:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14560:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14561:   free_matrix(matcov,1,npar,1,npar);
                   14562:   free_matrix(hess,1,npar,1,npar);
                   14563:   /*free_vector(delti,1,npar);*/
                   14564:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14565:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14566:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14567:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14568:   
                   14569:   free_ivector(ncodemax,1,NCOVMAX);
                   14570:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14571:   free_ivector(Dummy,-1,NCOVMAX);
                   14572:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14573:   free_ivector(DummyV,1,NCOVMAX);
                   14574:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14575:   free_ivector(Typevar,-1,NCOVMAX);
                   14576:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14577:   free_ivector(TvarsQ,1,NCOVMAX);
                   14578:   free_ivector(TvarsQind,1,NCOVMAX);
                   14579:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14580:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14581:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14582:   free_ivector(TvarFD,1,NCOVMAX);
                   14583:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14584:   free_ivector(TvarF,1,NCOVMAX);
                   14585:   free_ivector(TvarFind,1,NCOVMAX);
                   14586:   free_ivector(TvarV,1,NCOVMAX);
                   14587:   free_ivector(TvarVind,1,NCOVMAX);
                   14588:   free_ivector(TvarA,1,NCOVMAX);
                   14589:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14590:   free_ivector(TvarFQ,1,NCOVMAX);
                   14591:   free_ivector(TvarFQind,1,NCOVMAX);
                   14592:   free_ivector(TvarVD,1,NCOVMAX);
                   14593:   free_ivector(TvarVDind,1,NCOVMAX);
                   14594:   free_ivector(TvarVQ,1,NCOVMAX);
                   14595:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14596:   free_ivector(TvarVV,1,NCOVMAX);
                   14597:   free_ivector(TvarVVind,1,NCOVMAX);
                   14598:   
1.230     brouard  14599:   free_ivector(Tvarsel,1,NCOVMAX);
                   14600:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14601:   free_ivector(Tposprod,1,NCOVMAX);
                   14602:   free_ivector(Tprod,1,NCOVMAX);
                   14603:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14604:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14605:   free_ivector(Tage,1,NCOVMAX);
                   14606:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14607:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14608:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14609: 
                   14610:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14611: 
1.227     brouard  14612:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14613:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14614:   fflush(fichtm);
                   14615:   fflush(ficgp);
                   14616:   
1.227     brouard  14617:   
1.126     brouard  14618:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14619:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14620:     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  14621:   }else{
                   14622:     printf("End of Imach\n");
                   14623:     fprintf(ficlog,"End of Imach\n");
                   14624:   }
                   14625:   printf("See log file on %s\n",filelog);
                   14626:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14627:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14628:   rend_time = time(NULL);  
                   14629:   end_time = *localtime(&rend_time);
                   14630:   /* tml = *localtime(&end_time.tm_sec); */
                   14631:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14632:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14633:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14634:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14635:   
1.157     brouard  14636:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14637:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14638:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14639:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14640: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14641:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14642:   fclose(fichtm);
                   14643:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14644:   fclose(fichtmcov);
                   14645:   fclose(ficgp);
                   14646:   fclose(ficlog);
                   14647:   /*------ End -----------*/
1.227     brouard  14648:   
1.281     brouard  14649: 
                   14650: /* Executes gnuplot */
1.227     brouard  14651:   
                   14652:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14653: #ifdef WIN32
1.227     brouard  14654:   if (_chdir(pathcd) != 0)
                   14655:     printf("Can't move to directory %s!\n",path);
                   14656:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14657: #else
1.227     brouard  14658:     if(chdir(pathcd) != 0)
                   14659:       printf("Can't move to directory %s!\n", path);
                   14660:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14661: #endif 
1.126     brouard  14662:     printf("Current directory %s!\n",pathcd);
                   14663:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14664:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14665: #ifdef _WIN32
1.126     brouard  14666:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14667: #endif
                   14668:   if(!stat(plotcmd,&info)){
1.158     brouard  14669:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14670:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14671:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14672:     }else
                   14673:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14674: #ifdef __unix
1.126     brouard  14675:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14676:     if(!stat(plotcmd,&info)){
1.158     brouard  14677:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14678:     }else
                   14679:       strcpy(pplotcmd,plotcmd);
                   14680: #endif
                   14681:   }else
                   14682:     strcpy(pplotcmd,plotcmd);
                   14683:   
                   14684:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14685:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14686:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14687:   
1.126     brouard  14688:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14689:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14690:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14691:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14692:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14693:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14694:       strcpy(plotcmd,pplotcmd);
                   14695:     }
1.126     brouard  14696:   }
1.158     brouard  14697:   printf(" Successful, please wait...");
1.126     brouard  14698:   while (z[0] != 'q') {
                   14699:     /* chdir(path); */
1.154     brouard  14700:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14701:     scanf("%s",z);
                   14702: /*     if (z[0] == 'c') system("./imach"); */
                   14703:     if (z[0] == 'e') {
1.158     brouard  14704: #ifdef __APPLE__
1.152     brouard  14705:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14706: #elif __linux
                   14707:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14708: #else
1.152     brouard  14709:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14710: #endif
                   14711:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14712:       system(pplotcmd);
1.126     brouard  14713:     }
                   14714:     else if (z[0] == 'g') system(plotcmd);
                   14715:     else if (z[0] == 'q') exit(0);
                   14716:   }
1.227     brouard  14717: end:
1.126     brouard  14718:   while (z[0] != 'q') {
1.195     brouard  14719:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14720:     scanf("%s",z);
                   14721:   }
1.283     brouard  14722:   printf("End\n");
1.282     brouard  14723:   exit(0);
1.126     brouard  14724: }

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