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

1.342   ! brouard     1: /* $Id: imach.c,v 1.341 2022/09/11 07:58:42 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.342   ! brouard     4:   Revision 1.341  2022/09/11 07:58:42  brouard
        !             5:   Summary: Version 0.99r38
        !             6: 
        !             7:   After adding change in cotvar.
        !             8: 
1.341     brouard     9:   Revision 1.340  2022/09/11 07:53:11  brouard
                     10:   Summary: Version imach 0.99r37
                     11: 
                     12:   * imach.c (Module): Adding timevarying products of any kinds,
                     13:   should work before shifting cotvar from ncovcol+nqv columns in
                     14:   order to have a correspondance between the column of cotvar and
                     15:   the id of column.
                     16: 
1.340     brouard    17:   Revision 1.339  2022/09/09 17:55:22  brouard
                     18:   Summary: version 0.99r37
                     19: 
                     20:   * imach.c (Module): Many improvements for fixing products of fixed
                     21:   timevarying as well as fixed * fixed, and test with quantitative
                     22:   covariate.
                     23: 
1.339     brouard    24:   Revision 1.338  2022/09/04 17:40:33  brouard
                     25:   Summary: 0.99r36
                     26: 
                     27:   * imach.c (Module): Now the easy runs i.e. without result or
                     28:   model=1+age only did not work. The defautl combination should be 1
                     29:   and not 0 because everything hasn't been tranformed yet.
                     30: 
1.338     brouard    31:   Revision 1.337  2022/09/02 14:26:02  brouard
                     32:   Summary: version 0.99r35
                     33: 
                     34:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     35:   1+age+V1+V1*age for females and 1+age for females only
                     36:   (education=1 noweight)
                     37: 
1.337     brouard    38:   Revision 1.336  2022/08/31 09:52:36  brouard
                     39:   *** empty log message ***
                     40: 
1.336     brouard    41:   Revision 1.335  2022/08/31 08:23:16  brouard
                     42:   Summary: improvements...
                     43: 
1.335     brouard    44:   Revision 1.334  2022/08/25 09:08:41  brouard
                     45:   Summary: In progress for quantitative
                     46: 
1.334     brouard    47:   Revision 1.333  2022/08/21 09:10:30  brouard
                     48:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     49:   reassigning covariates: my first idea was that people will always
                     50:   use the first covariate V1 into the model but in fact they are
                     51:   producing data with many covariates and can use an equation model
                     52:   with some of the covariate; it means that in a model V2+V3 instead
                     53:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     54:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     55:   the equation model is restricted to two variables only (V2, V3)
                     56:   and the combination for V2 should be codtabm(k,1) instead of
                     57:   (codtabm(k,2), and the code should be
                     58:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     59:   made. All of these should be simplified once a day like we did in
                     60:   hpxij() for example by using precov[nres] which is computed in
                     61:   decoderesult for each nres of each resultline. Loop should be done
                     62:   on the equation model globally by distinguishing only product with
                     63:   age (which are changing with age) and no more on type of
                     64:   covariates, single dummies, single covariates.
                     65: 
1.333     brouard    66:   Revision 1.332  2022/08/21 09:06:25  brouard
                     67:   Summary: Version 0.99r33
                     68: 
                     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.332     brouard    87:   Revision 1.331  2022/08/07 05:40:09  brouard
                     88:   *** empty log message ***
                     89: 
1.331     brouard    90:   Revision 1.330  2022/08/06 07:18:25  brouard
                     91:   Summary: last 0.99r31
                     92: 
                     93:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     94: 
1.330     brouard    95:   Revision 1.329  2022/08/03 17:29:54  brouard
                     96:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     97: 
1.329     brouard    98:   Revision 1.328  2022/07/27 17:40:48  brouard
                     99:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    100: 
1.328     brouard   101:   Revision 1.327  2022/07/27 14:47:35  brouard
                    102:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    103: 
1.327     brouard   104:   Revision 1.326  2022/07/26 17:33:55  brouard
                    105:   Summary: some test with nres=1
                    106: 
1.326     brouard   107:   Revision 1.325  2022/07/25 14:27:23  brouard
                    108:   Summary: r30
                    109: 
                    110:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    111:   coredumped, revealed by Feiuno, thank you.
                    112: 
1.325     brouard   113:   Revision 1.324  2022/07/23 17:44:26  brouard
                    114:   *** empty log message ***
                    115: 
1.324     brouard   116:   Revision 1.323  2022/07/22 12:30:08  brouard
                    117:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    118: 
1.323     brouard   119:   Revision 1.322  2022/07/22 12:27:48  brouard
                    120:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    121: 
1.322     brouard   122:   Revision 1.321  2022/07/22 12:04:24  brouard
                    123:   Summary: r28
                    124: 
                    125:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    126: 
1.321     brouard   127:   Revision 1.320  2022/06/02 05:10:11  brouard
                    128:   *** empty log message ***
                    129: 
1.320     brouard   130:   Revision 1.319  2022/06/02 04:45:11  brouard
                    131:   * imach.c (Module): Adding the Wald tests from the log to the main
                    132:   htm for better display of the maximum likelihood estimators.
                    133: 
1.319     brouard   134:   Revision 1.318  2022/05/24 08:10:59  brouard
                    135:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    136:   of confidencce intervals with product in the equation modelC
                    137: 
1.318     brouard   138:   Revision 1.317  2022/05/15 15:06:23  brouard
                    139:   * imach.c (Module):  Some minor improvements
                    140: 
1.317     brouard   141:   Revision 1.316  2022/05/11 15:11:31  brouard
                    142:   Summary: r27
                    143: 
1.316     brouard   144:   Revision 1.315  2022/05/11 15:06:32  brouard
                    145:   *** empty log message ***
                    146: 
1.315     brouard   147:   Revision 1.314  2022/04/13 17:43:09  brouard
                    148:   * imach.c (Module): Adding link to text data files
                    149: 
1.314     brouard   150:   Revision 1.313  2022/04/11 15:57:42  brouard
                    151:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    152: 
1.313     brouard   153:   Revision 1.312  2022/04/05 21:24:39  brouard
                    154:   *** empty log message ***
                    155: 
1.312     brouard   156:   Revision 1.311  2022/04/05 21:03:51  brouard
                    157:   Summary: Fixed quantitative covariates
                    158: 
                    159:          Fixed covariates (dummy or quantitative)
                    160:        with missing values have never been allowed but are ERRORS and
                    161:        program quits. Standard deviations of fixed covariates were
                    162:        wrongly computed. Mean and standard deviations of time varying
                    163:        covariates are still not computed.
                    164: 
1.311     brouard   165:   Revision 1.310  2022/03/17 08:45:53  brouard
                    166:   Summary: 99r25
                    167: 
                    168:   Improving detection of errors: result lines should be compatible with
                    169:   the model.
                    170: 
1.310     brouard   171:   Revision 1.309  2021/05/20 12:39:14  brouard
                    172:   Summary: Version 0.99r24
                    173: 
1.309     brouard   174:   Revision 1.308  2021/03/31 13:11:57  brouard
                    175:   Summary: Version 0.99r23
                    176: 
                    177: 
                    178:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    179: 
1.308     brouard   180:   Revision 1.307  2021/03/08 18:11:32  brouard
                    181:   Summary: 0.99r22 fixed bug on result:
                    182: 
1.307     brouard   183:   Revision 1.306  2021/02/20 15:44:02  brouard
                    184:   Summary: Version 0.99r21
                    185: 
                    186:   * imach.c (Module): Fix bug on quitting after result lines!
                    187:   (Module): Version 0.99r21
                    188: 
1.306     brouard   189:   Revision 1.305  2021/02/20 15:28:30  brouard
                    190:   * imach.c (Module): Fix bug on quitting after result lines!
                    191: 
1.305     brouard   192:   Revision 1.304  2021/02/12 11:34:20  brouard
                    193:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    194: 
1.304     brouard   195:   Revision 1.303  2021/02/11 19:50:15  brouard
                    196:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    197: 
1.303     brouard   198:   Revision 1.302  2020/02/22 21:00:05  brouard
                    199:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    200:   and life table from the data without any state)
                    201: 
1.302     brouard   202:   Revision 1.301  2019/06/04 13:51:20  brouard
                    203:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    204: 
1.301     brouard   205:   Revision 1.300  2019/05/22 19:09:45  brouard
                    206:   Summary: version 0.99r19 of May 2019
                    207: 
1.300     brouard   208:   Revision 1.299  2019/05/22 18:37:08  brouard
                    209:   Summary: Cleaned 0.99r19
                    210: 
1.299     brouard   211:   Revision 1.298  2019/05/22 18:19:56  brouard
                    212:   *** empty log message ***
                    213: 
1.298     brouard   214:   Revision 1.297  2019/05/22 17:56:10  brouard
                    215:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    216: 
1.297     brouard   217:   Revision 1.296  2019/05/20 13:03:18  brouard
                    218:   Summary: Projection syntax simplified
                    219: 
                    220: 
                    221:   We can now start projections, forward or backward, from the mean date
                    222:   of inteviews up to or down to a number of years of projection:
                    223:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    224:   or
                    225:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    226:   or
                    227:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    228:   or
                    229:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    230: 
1.296     brouard   231:   Revision 1.295  2019/05/18 09:52:50  brouard
                    232:   Summary: doxygen tex bug
                    233: 
1.295     brouard   234:   Revision 1.294  2019/05/16 14:54:33  brouard
                    235:   Summary: There was some wrong lines added
                    236: 
1.294     brouard   237:   Revision 1.293  2019/05/09 15:17:34  brouard
                    238:   *** empty log message ***
                    239: 
1.293     brouard   240:   Revision 1.292  2019/05/09 14:17:20  brouard
                    241:   Summary: Some updates
                    242: 
1.292     brouard   243:   Revision 1.291  2019/05/09 13:44:18  brouard
                    244:   Summary: Before ncovmax
                    245: 
1.291     brouard   246:   Revision 1.290  2019/05/09 13:39:37  brouard
                    247:   Summary: 0.99r18 unlimited number of individuals
                    248: 
                    249:   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.
                    250: 
1.290     brouard   251:   Revision 1.289  2018/12/13 09:16:26  brouard
                    252:   Summary: Bug for young ages (<-30) will be in r17
                    253: 
1.289     brouard   254:   Revision 1.288  2018/05/02 20:58:27  brouard
                    255:   Summary: Some bugs fixed
                    256: 
1.288     brouard   257:   Revision 1.287  2018/05/01 17:57:25  brouard
                    258:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    259: 
1.287     brouard   260:   Revision 1.286  2018/04/27 14:27:04  brouard
                    261:   Summary: some minor bugs
                    262: 
1.286     brouard   263:   Revision 1.285  2018/04/21 21:02:16  brouard
                    264:   Summary: Some bugs fixed, valgrind tested
                    265: 
1.285     brouard   266:   Revision 1.284  2018/04/20 05:22:13  brouard
                    267:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    268: 
1.284     brouard   269:   Revision 1.283  2018/04/19 14:49:16  brouard
                    270:   Summary: Some minor bugs fixed
                    271: 
1.283     brouard   272:   Revision 1.282  2018/02/27 22:50:02  brouard
                    273:   *** empty log message ***
                    274: 
1.282     brouard   275:   Revision 1.281  2018/02/27 19:25:23  brouard
                    276:   Summary: Adding second argument for quitting
                    277: 
1.281     brouard   278:   Revision 1.280  2018/02/21 07:58:13  brouard
                    279:   Summary: 0.99r15
                    280: 
                    281:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    282: 
1.280     brouard   283:   Revision 1.279  2017/07/20 13:35:01  brouard
                    284:   Summary: temporary working
                    285: 
1.279     brouard   286:   Revision 1.278  2017/07/19 14:09:02  brouard
                    287:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    288: 
1.278     brouard   289:   Revision 1.277  2017/07/17 08:53:49  brouard
                    290:   Summary: BOM files can be read now
                    291: 
1.277     brouard   292:   Revision 1.276  2017/06/30 15:48:31  brouard
                    293:   Summary: Graphs improvements
                    294: 
1.276     brouard   295:   Revision 1.275  2017/06/30 13:39:33  brouard
                    296:   Summary: Saito's color
                    297: 
1.275     brouard   298:   Revision 1.274  2017/06/29 09:47:08  brouard
                    299:   Summary: Version 0.99r14
                    300: 
1.274     brouard   301:   Revision 1.273  2017/06/27 11:06:02  brouard
                    302:   Summary: More documentation on projections
                    303: 
1.273     brouard   304:   Revision 1.272  2017/06/27 10:22:40  brouard
                    305:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    306: 
1.272     brouard   307:   Revision 1.271  2017/06/27 10:17:50  brouard
                    308:   Summary: Some bug with rint
                    309: 
1.271     brouard   310:   Revision 1.270  2017/05/24 05:45:29  brouard
                    311:   *** empty log message ***
                    312: 
1.270     brouard   313:   Revision 1.269  2017/05/23 08:39:25  brouard
                    314:   Summary: Code into subroutine, cleanings
                    315: 
1.269     brouard   316:   Revision 1.268  2017/05/18 20:09:32  brouard
                    317:   Summary: backprojection and confidence intervals of backprevalence
                    318: 
1.268     brouard   319:   Revision 1.267  2017/05/13 10:25:05  brouard
                    320:   Summary: temporary save for backprojection
                    321: 
1.267     brouard   322:   Revision 1.266  2017/05/13 07:26:12  brouard
                    323:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    324: 
1.266     brouard   325:   Revision 1.265  2017/04/26 16:22:11  brouard
                    326:   Summary: imach 0.99r13 Some bugs fixed
                    327: 
1.265     brouard   328:   Revision 1.264  2017/04/26 06:01:29  brouard
                    329:   Summary: Labels in graphs
                    330: 
1.264     brouard   331:   Revision 1.263  2017/04/24 15:23:15  brouard
                    332:   Summary: to save
                    333: 
1.263     brouard   334:   Revision 1.262  2017/04/18 16:48:12  brouard
                    335:   *** empty log message ***
                    336: 
1.262     brouard   337:   Revision 1.261  2017/04/05 10:14:09  brouard
                    338:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    339: 
1.261     brouard   340:   Revision 1.260  2017/04/04 17:46:59  brouard
                    341:   Summary: Gnuplot indexations fixed (humm)
                    342: 
1.260     brouard   343:   Revision 1.259  2017/04/04 13:01:16  brouard
                    344:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    345: 
1.259     brouard   346:   Revision 1.258  2017/04/03 10:17:47  brouard
                    347:   Summary: Version 0.99r12
                    348: 
                    349:   Some cleanings, conformed with updated documentation.
                    350: 
1.258     brouard   351:   Revision 1.257  2017/03/29 16:53:30  brouard
                    352:   Summary: Temp
                    353: 
1.257     brouard   354:   Revision 1.256  2017/03/27 05:50:23  brouard
                    355:   Summary: Temporary
                    356: 
1.256     brouard   357:   Revision 1.255  2017/03/08 16:02:28  brouard
                    358:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    359: 
1.255     brouard   360:   Revision 1.254  2017/03/08 07:13:00  brouard
                    361:   Summary: Fixing data parameter line
                    362: 
1.254     brouard   363:   Revision 1.253  2016/12/15 11:59:41  brouard
                    364:   Summary: 0.99 in progress
                    365: 
1.253     brouard   366:   Revision 1.252  2016/09/15 21:15:37  brouard
                    367:   *** empty log message ***
                    368: 
1.252     brouard   369:   Revision 1.251  2016/09/15 15:01:13  brouard
                    370:   Summary: not working
                    371: 
1.251     brouard   372:   Revision 1.250  2016/09/08 16:07:27  brouard
                    373:   Summary: continue
                    374: 
1.250     brouard   375:   Revision 1.249  2016/09/07 17:14:18  brouard
                    376:   Summary: Starting values from frequencies
                    377: 
1.249     brouard   378:   Revision 1.248  2016/09/07 14:10:18  brouard
                    379:   *** empty log message ***
                    380: 
1.248     brouard   381:   Revision 1.247  2016/09/02 11:11:21  brouard
                    382:   *** empty log message ***
                    383: 
1.247     brouard   384:   Revision 1.246  2016/09/02 08:49:22  brouard
                    385:   *** empty log message ***
                    386: 
1.246     brouard   387:   Revision 1.245  2016/09/02 07:25:01  brouard
                    388:   *** empty log message ***
                    389: 
1.245     brouard   390:   Revision 1.244  2016/09/02 07:17:34  brouard
                    391:   *** empty log message ***
                    392: 
1.244     brouard   393:   Revision 1.243  2016/09/02 06:45:35  brouard
                    394:   *** empty log message ***
                    395: 
1.243     brouard   396:   Revision 1.242  2016/08/30 15:01:20  brouard
                    397:   Summary: Fixing a lots
                    398: 
1.242     brouard   399:   Revision 1.241  2016/08/29 17:17:25  brouard
                    400:   Summary: gnuplot problem in Back projection to fix
                    401: 
1.241     brouard   402:   Revision 1.240  2016/08/29 07:53:18  brouard
                    403:   Summary: Better
                    404: 
1.240     brouard   405:   Revision 1.239  2016/08/26 15:51:03  brouard
                    406:   Summary: Improvement in Powell output in order to copy and paste
                    407: 
                    408:   Author:
                    409: 
1.239     brouard   410:   Revision 1.238  2016/08/26 14:23:35  brouard
                    411:   Summary: Starting tests of 0.99
                    412: 
1.238     brouard   413:   Revision 1.237  2016/08/26 09:20:19  brouard
                    414:   Summary: to valgrind
                    415: 
1.237     brouard   416:   Revision 1.236  2016/08/25 10:50:18  brouard
                    417:   *** empty log message ***
                    418: 
1.236     brouard   419:   Revision 1.235  2016/08/25 06:59:23  brouard
                    420:   *** empty log message ***
                    421: 
1.235     brouard   422:   Revision 1.234  2016/08/23 16:51:20  brouard
                    423:   *** empty log message ***
                    424: 
1.234     brouard   425:   Revision 1.233  2016/08/23 07:40:50  brouard
                    426:   Summary: not working
                    427: 
1.233     brouard   428:   Revision 1.232  2016/08/22 14:20:21  brouard
                    429:   Summary: not working
                    430: 
1.232     brouard   431:   Revision 1.231  2016/08/22 07:17:15  brouard
                    432:   Summary: not working
                    433: 
1.231     brouard   434:   Revision 1.230  2016/08/22 06:55:53  brouard
                    435:   Summary: Not working
                    436: 
1.230     brouard   437:   Revision 1.229  2016/07/23 09:45:53  brouard
                    438:   Summary: Completing for func too
                    439: 
1.229     brouard   440:   Revision 1.228  2016/07/22 17:45:30  brouard
                    441:   Summary: Fixing some arrays, still debugging
                    442: 
1.227     brouard   443:   Revision 1.226  2016/07/12 18:42:34  brouard
                    444:   Summary: temp
                    445: 
1.226     brouard   446:   Revision 1.225  2016/07/12 08:40:03  brouard
                    447:   Summary: saving but not running
                    448: 
1.225     brouard   449:   Revision 1.224  2016/07/01 13:16:01  brouard
                    450:   Summary: Fixes
                    451: 
1.224     brouard   452:   Revision 1.223  2016/02/19 09:23:35  brouard
                    453:   Summary: temporary
                    454: 
1.223     brouard   455:   Revision 1.222  2016/02/17 08:14:50  brouard
                    456:   Summary: Probably last 0.98 stable version 0.98r6
                    457: 
1.222     brouard   458:   Revision 1.221  2016/02/15 23:35:36  brouard
                    459:   Summary: minor bug
                    460: 
1.220     brouard   461:   Revision 1.219  2016/02/15 00:48:12  brouard
                    462:   *** empty log message ***
                    463: 
1.219     brouard   464:   Revision 1.218  2016/02/12 11:29:23  brouard
                    465:   Summary: 0.99 Back projections
                    466: 
1.218     brouard   467:   Revision 1.217  2015/12/23 17:18:31  brouard
                    468:   Summary: Experimental backcast
                    469: 
1.217     brouard   470:   Revision 1.216  2015/12/18 17:32:11  brouard
                    471:   Summary: 0.98r4 Warning and status=-2
                    472: 
                    473:   Version 0.98r4 is now:
                    474:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    475:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    476:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    477: 
1.216     brouard   478:   Revision 1.215  2015/12/16 08:52:24  brouard
                    479:   Summary: 0.98r4 working
                    480: 
1.215     brouard   481:   Revision 1.214  2015/12/16 06:57:54  brouard
                    482:   Summary: temporary not working
                    483: 
1.214     brouard   484:   Revision 1.213  2015/12/11 18:22:17  brouard
                    485:   Summary: 0.98r4
                    486: 
1.213     brouard   487:   Revision 1.212  2015/11/21 12:47:24  brouard
                    488:   Summary: minor typo
                    489: 
1.212     brouard   490:   Revision 1.211  2015/11/21 12:41:11  brouard
                    491:   Summary: 0.98r3 with some graph of projected cross-sectional
                    492: 
                    493:   Author: Nicolas Brouard
                    494: 
1.211     brouard   495:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   496:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   497:   Summary: Adding ftolpl parameter
                    498:   Author: N Brouard
                    499: 
                    500:   We had difficulties to get smoothed confidence intervals. It was due
                    501:   to the period prevalence which wasn't computed accurately. The inner
                    502:   parameter ftolpl is now an outer parameter of the .imach parameter
                    503:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    504:   computation are long.
                    505: 
1.209     brouard   506:   Revision 1.208  2015/11/17 14:31:57  brouard
                    507:   Summary: temporary
                    508: 
1.208     brouard   509:   Revision 1.207  2015/10/27 17:36:57  brouard
                    510:   *** empty log message ***
                    511: 
1.207     brouard   512:   Revision 1.206  2015/10/24 07:14:11  brouard
                    513:   *** empty log message ***
                    514: 
1.206     brouard   515:   Revision 1.205  2015/10/23 15:50:53  brouard
                    516:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    517: 
1.205     brouard   518:   Revision 1.204  2015/10/01 16:20:26  brouard
                    519:   Summary: Some new graphs of contribution to likelihood
                    520: 
1.204     brouard   521:   Revision 1.203  2015/09/30 17:45:14  brouard
                    522:   Summary: looking at better estimation of the hessian
                    523: 
                    524:   Also a better criteria for convergence to the period prevalence And
                    525:   therefore adding the number of years needed to converge. (The
                    526:   prevalence in any alive state shold sum to one
                    527: 
1.203     brouard   528:   Revision 1.202  2015/09/22 19:45:16  brouard
                    529:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    530: 
1.202     brouard   531:   Revision 1.201  2015/09/15 17:34:58  brouard
                    532:   Summary: 0.98r0
                    533: 
                    534:   - Some new graphs like suvival functions
                    535:   - Some bugs fixed like model=1+age+V2.
                    536: 
1.201     brouard   537:   Revision 1.200  2015/09/09 16:53:55  brouard
                    538:   Summary: Big bug thanks to Flavia
                    539: 
                    540:   Even model=1+age+V2. did not work anymore
                    541: 
1.200     brouard   542:   Revision 1.199  2015/09/07 14:09:23  brouard
                    543:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    544: 
1.199     brouard   545:   Revision 1.198  2015/09/03 07:14:39  brouard
                    546:   Summary: 0.98q5 Flavia
                    547: 
1.198     brouard   548:   Revision 1.197  2015/09/01 18:24:39  brouard
                    549:   *** empty log message ***
                    550: 
1.197     brouard   551:   Revision 1.196  2015/08/18 23:17:52  brouard
                    552:   Summary: 0.98q5
                    553: 
1.196     brouard   554:   Revision 1.195  2015/08/18 16:28:39  brouard
                    555:   Summary: Adding a hack for testing purpose
                    556: 
                    557:   After reading the title, ftol and model lines, if the comment line has
                    558:   a q, starting with #q, the answer at the end of the run is quit. It
                    559:   permits to run test files in batch with ctest. The former workaround was
                    560:   $ echo q | imach foo.imach
                    561: 
1.195     brouard   562:   Revision 1.194  2015/08/18 13:32:00  brouard
                    563:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    564: 
1.194     brouard   565:   Revision 1.193  2015/08/04 07:17:42  brouard
                    566:   Summary: 0.98q4
                    567: 
1.193     brouard   568:   Revision 1.192  2015/07/16 16:49:02  brouard
                    569:   Summary: Fixing some outputs
                    570: 
1.192     brouard   571:   Revision 1.191  2015/07/14 10:00:33  brouard
                    572:   Summary: Some fixes
                    573: 
1.191     brouard   574:   Revision 1.190  2015/05/05 08:51:13  brouard
                    575:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    576: 
                    577:   Fix 1+age+.
                    578: 
1.190     brouard   579:   Revision 1.189  2015/04/30 14:45:16  brouard
                    580:   Summary: 0.98q2
                    581: 
1.189     brouard   582:   Revision 1.188  2015/04/30 08:27:53  brouard
                    583:   *** empty log message ***
                    584: 
1.188     brouard   585:   Revision 1.187  2015/04/29 09:11:15  brouard
                    586:   *** empty log message ***
                    587: 
1.187     brouard   588:   Revision 1.186  2015/04/23 12:01:52  brouard
                    589:   Summary: V1*age is working now, version 0.98q1
                    590: 
                    591:   Some codes had been disabled in order to simplify and Vn*age was
                    592:   working in the optimization phase, ie, giving correct MLE parameters,
                    593:   but, as usual, outputs were not correct and program core dumped.
                    594: 
1.186     brouard   595:   Revision 1.185  2015/03/11 13:26:42  brouard
                    596:   Summary: Inclusion of compile and links command line for Intel Compiler
                    597: 
1.185     brouard   598:   Revision 1.184  2015/03/11 11:52:39  brouard
                    599:   Summary: Back from Windows 8. Intel Compiler
                    600: 
1.184     brouard   601:   Revision 1.183  2015/03/10 20:34:32  brouard
                    602:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    603: 
                    604:   We use directest instead of original Powell test; probably no
                    605:   incidence on the results, but better justifications;
                    606:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    607:   wrong results.
                    608: 
1.183     brouard   609:   Revision 1.182  2015/02/12 08:19:57  brouard
                    610:   Summary: Trying to keep directest which seems simpler and more general
                    611:   Author: Nicolas Brouard
                    612: 
1.182     brouard   613:   Revision 1.181  2015/02/11 23:22:24  brouard
                    614:   Summary: Comments on Powell added
                    615: 
                    616:   Author:
                    617: 
1.181     brouard   618:   Revision 1.180  2015/02/11 17:33:45  brouard
                    619:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    620: 
1.180     brouard   621:   Revision 1.179  2015/01/04 09:57:06  brouard
                    622:   Summary: back to OS/X
                    623: 
1.179     brouard   624:   Revision 1.178  2015/01/04 09:35:48  brouard
                    625:   *** empty log message ***
                    626: 
1.178     brouard   627:   Revision 1.177  2015/01/03 18:40:56  brouard
                    628:   Summary: Still testing ilc32 on OSX
                    629: 
1.177     brouard   630:   Revision 1.176  2015/01/03 16:45:04  brouard
                    631:   *** empty log message ***
                    632: 
1.176     brouard   633:   Revision 1.175  2015/01/03 16:33:42  brouard
                    634:   *** empty log message ***
                    635: 
1.175     brouard   636:   Revision 1.174  2015/01/03 16:15:49  brouard
                    637:   Summary: Still in cross-compilation
                    638: 
1.174     brouard   639:   Revision 1.173  2015/01/03 12:06:26  brouard
                    640:   Summary: trying to detect cross-compilation
                    641: 
1.173     brouard   642:   Revision 1.172  2014/12/27 12:07:47  brouard
                    643:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    644: 
1.172     brouard   645:   Revision 1.171  2014/12/23 13:26:59  brouard
                    646:   Summary: Back from Visual C
                    647: 
                    648:   Still problem with utsname.h on Windows
                    649: 
1.171     brouard   650:   Revision 1.170  2014/12/23 11:17:12  brouard
                    651:   Summary: Cleaning some \%% back to %%
                    652: 
                    653:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    654: 
1.170     brouard   655:   Revision 1.169  2014/12/22 23:08:31  brouard
                    656:   Summary: 0.98p
                    657: 
                    658:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    659: 
1.169     brouard   660:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   661:   Summary: update
1.169     brouard   662: 
1.168     brouard   663:   Revision 1.167  2014/12/22 13:50:56  brouard
                    664:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    665: 
                    666:   Testing on Linux 64
                    667: 
1.167     brouard   668:   Revision 1.166  2014/12/22 11:40:47  brouard
                    669:   *** empty log message ***
                    670: 
1.166     brouard   671:   Revision 1.165  2014/12/16 11:20:36  brouard
                    672:   Summary: After compiling on Visual C
                    673: 
                    674:   * imach.c (Module): Merging 1.61 to 1.162
                    675: 
1.165     brouard   676:   Revision 1.164  2014/12/16 10:52:11  brouard
                    677:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    678: 
                    679:   * imach.c (Module): Merging 1.61 to 1.162
                    680: 
1.164     brouard   681:   Revision 1.163  2014/12/16 10:30:11  brouard
                    682:   * imach.c (Module): Merging 1.61 to 1.162
                    683: 
1.163     brouard   684:   Revision 1.162  2014/09/25 11:43:39  brouard
                    685:   Summary: temporary backup 0.99!
                    686: 
1.162     brouard   687:   Revision 1.1  2014/09/16 11:06:58  brouard
                    688:   Summary: With some code (wrong) for nlopt
                    689: 
                    690:   Author:
                    691: 
                    692:   Revision 1.161  2014/09/15 20:41:41  brouard
                    693:   Summary: Problem with macro SQR on Intel compiler
                    694: 
1.161     brouard   695:   Revision 1.160  2014/09/02 09:24:05  brouard
                    696:   *** empty log message ***
                    697: 
1.160     brouard   698:   Revision 1.159  2014/09/01 10:34:10  brouard
                    699:   Summary: WIN32
                    700:   Author: Brouard
                    701: 
1.159     brouard   702:   Revision 1.158  2014/08/27 17:11:51  brouard
                    703:   *** empty log message ***
                    704: 
1.158     brouard   705:   Revision 1.157  2014/08/27 16:26:55  brouard
                    706:   Summary: Preparing windows Visual studio version
                    707:   Author: Brouard
                    708: 
                    709:   In order to compile on Visual studio, time.h is now correct and time_t
                    710:   and tm struct should be used. difftime should be used but sometimes I
                    711:   just make the differences in raw time format (time(&now).
                    712:   Trying to suppress #ifdef LINUX
                    713:   Add xdg-open for __linux in order to open default browser.
                    714: 
1.157     brouard   715:   Revision 1.156  2014/08/25 20:10:10  brouard
                    716:   *** empty log message ***
                    717: 
1.156     brouard   718:   Revision 1.155  2014/08/25 18:32:34  brouard
                    719:   Summary: New compile, minor changes
                    720:   Author: Brouard
                    721: 
1.155     brouard   722:   Revision 1.154  2014/06/20 17:32:08  brouard
                    723:   Summary: Outputs now all graphs of convergence to period prevalence
                    724: 
1.154     brouard   725:   Revision 1.153  2014/06/20 16:45:46  brouard
                    726:   Summary: If 3 live state, convergence to period prevalence on same graph
                    727:   Author: Brouard
                    728: 
1.153     brouard   729:   Revision 1.152  2014/06/18 17:54:09  brouard
                    730:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    731: 
1.152     brouard   732:   Revision 1.151  2014/06/18 16:43:30  brouard
                    733:   *** empty log message ***
                    734: 
1.151     brouard   735:   Revision 1.150  2014/06/18 16:42:35  brouard
                    736:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    737:   Author: brouard
                    738: 
1.150     brouard   739:   Revision 1.149  2014/06/18 15:51:14  brouard
                    740:   Summary: Some fixes in parameter files errors
                    741:   Author: Nicolas Brouard
                    742: 
1.149     brouard   743:   Revision 1.148  2014/06/17 17:38:48  brouard
                    744:   Summary: Nothing new
                    745:   Author: Brouard
                    746: 
                    747:   Just a new packaging for OS/X version 0.98nS
                    748: 
1.148     brouard   749:   Revision 1.147  2014/06/16 10:33:11  brouard
                    750:   *** empty log message ***
                    751: 
1.147     brouard   752:   Revision 1.146  2014/06/16 10:20:28  brouard
                    753:   Summary: Merge
                    754:   Author: Brouard
                    755: 
                    756:   Merge, before building revised version.
                    757: 
1.146     brouard   758:   Revision 1.145  2014/06/10 21:23:15  brouard
                    759:   Summary: Debugging with valgrind
                    760:   Author: Nicolas Brouard
                    761: 
                    762:   Lot of changes in order to output the results with some covariates
                    763:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    764:   improve the code.
                    765:   No more memory valgrind error but a lot has to be done in order to
                    766:   continue the work of splitting the code into subroutines.
                    767:   Also, decodemodel has been improved. Tricode is still not
                    768:   optimal. nbcode should be improved. Documentation has been added in
                    769:   the source code.
                    770: 
1.144     brouard   771:   Revision 1.143  2014/01/26 09:45:38  brouard
                    772:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    773: 
                    774:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    775:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    776: 
1.143     brouard   777:   Revision 1.142  2014/01/26 03:57:36  brouard
                    778:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    779: 
                    780:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    781: 
1.142     brouard   782:   Revision 1.141  2014/01/26 02:42:01  brouard
                    783:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    784: 
1.141     brouard   785:   Revision 1.140  2011/09/02 10:37:54  brouard
                    786:   Summary: times.h is ok with mingw32 now.
                    787: 
1.140     brouard   788:   Revision 1.139  2010/06/14 07:50:17  brouard
                    789:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    790:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    791: 
1.139     brouard   792:   Revision 1.138  2010/04/30 18:19:40  brouard
                    793:   *** empty log message ***
                    794: 
1.138     brouard   795:   Revision 1.137  2010/04/29 18:11:38  brouard
                    796:   (Module): Checking covariates for more complex models
                    797:   than V1+V2. A lot of change to be done. Unstable.
                    798: 
1.137     brouard   799:   Revision 1.136  2010/04/26 20:30:53  brouard
                    800:   (Module): merging some libgsl code. Fixing computation
                    801:   of likelione (using inter/intrapolation if mle = 0) in order to
                    802:   get same likelihood as if mle=1.
                    803:   Some cleaning of code and comments added.
                    804: 
1.136     brouard   805:   Revision 1.135  2009/10/29 15:33:14  brouard
                    806:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    807: 
1.135     brouard   808:   Revision 1.134  2009/10/29 13:18:53  brouard
                    809:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    810: 
1.134     brouard   811:   Revision 1.133  2009/07/06 10:21:25  brouard
                    812:   just nforces
                    813: 
1.133     brouard   814:   Revision 1.132  2009/07/06 08:22:05  brouard
                    815:   Many tings
                    816: 
1.132     brouard   817:   Revision 1.131  2009/06/20 16:22:47  brouard
                    818:   Some dimensions resccaled
                    819: 
1.131     brouard   820:   Revision 1.130  2009/05/26 06:44:34  brouard
                    821:   (Module): Max Covariate is now set to 20 instead of 8. A
                    822:   lot of cleaning with variables initialized to 0. Trying to make
                    823:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    824: 
1.130     brouard   825:   Revision 1.129  2007/08/31 13:49:27  lievre
                    826:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    827: 
1.129     lievre    828:   Revision 1.128  2006/06/30 13:02:05  brouard
                    829:   (Module): Clarifications on computing e.j
                    830: 
1.128     brouard   831:   Revision 1.127  2006/04/28 18:11:50  brouard
                    832:   (Module): Yes the sum of survivors was wrong since
                    833:   imach-114 because nhstepm was no more computed in the age
                    834:   loop. Now we define nhstepma in the age loop.
                    835:   (Module): In order to speed up (in case of numerous covariates) we
                    836:   compute health expectancies (without variances) in a first step
                    837:   and then all the health expectancies with variances or standard
                    838:   deviation (needs data from the Hessian matrices) which slows the
                    839:   computation.
                    840:   In the future we should be able to stop the program is only health
                    841:   expectancies and graph are needed without standard deviations.
                    842: 
1.127     brouard   843:   Revision 1.126  2006/04/28 17:23:28  brouard
                    844:   (Module): Yes the sum of survivors was wrong since
                    845:   imach-114 because nhstepm was no more computed in the age
                    846:   loop. Now we define nhstepma in the age loop.
                    847:   Version 0.98h
                    848: 
1.126     brouard   849:   Revision 1.125  2006/04/04 15:20:31  lievre
                    850:   Errors in calculation of health expectancies. Age was not initialized.
                    851:   Forecasting file added.
                    852: 
                    853:   Revision 1.124  2006/03/22 17:13:53  lievre
                    854:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    855:   The log-likelihood is printed in the log file
                    856: 
                    857:   Revision 1.123  2006/03/20 10:52:43  brouard
                    858:   * imach.c (Module): <title> changed, corresponds to .htm file
                    859:   name. <head> headers where missing.
                    860: 
                    861:   * imach.c (Module): Weights can have a decimal point as for
                    862:   English (a comma might work with a correct LC_NUMERIC environment,
                    863:   otherwise the weight is truncated).
                    864:   Modification of warning when the covariates values are not 0 or
                    865:   1.
                    866:   Version 0.98g
                    867: 
                    868:   Revision 1.122  2006/03/20 09:45:41  brouard
                    869:   (Module): Weights can have a decimal point as for
                    870:   English (a comma might work with a correct LC_NUMERIC environment,
                    871:   otherwise the weight is truncated).
                    872:   Modification of warning when the covariates values are not 0 or
                    873:   1.
                    874:   Version 0.98g
                    875: 
                    876:   Revision 1.121  2006/03/16 17:45:01  lievre
                    877:   * imach.c (Module): Comments concerning covariates added
                    878: 
                    879:   * imach.c (Module): refinements in the computation of lli if
                    880:   status=-2 in order to have more reliable computation if stepm is
                    881:   not 1 month. Version 0.98f
                    882: 
                    883:   Revision 1.120  2006/03/16 15:10:38  lievre
                    884:   (Module): refinements in the computation of lli if
                    885:   status=-2 in order to have more reliable computation if stepm is
                    886:   not 1 month. Version 0.98f
                    887: 
                    888:   Revision 1.119  2006/03/15 17:42:26  brouard
                    889:   (Module): Bug if status = -2, the loglikelihood was
                    890:   computed as likelihood omitting the logarithm. Version O.98e
                    891: 
                    892:   Revision 1.118  2006/03/14 18:20:07  brouard
                    893:   (Module): varevsij Comments added explaining the second
                    894:   table of variances if popbased=1 .
                    895:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    896:   (Module): Function pstamp added
                    897:   (Module): Version 0.98d
                    898: 
                    899:   Revision 1.117  2006/03/14 17:16:22  brouard
                    900:   (Module): varevsij Comments added explaining the second
                    901:   table of variances if popbased=1 .
                    902:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    903:   (Module): Function pstamp added
                    904:   (Module): Version 0.98d
                    905: 
                    906:   Revision 1.116  2006/03/06 10:29:27  brouard
                    907:   (Module): Variance-covariance wrong links and
                    908:   varian-covariance of ej. is needed (Saito).
                    909: 
                    910:   Revision 1.115  2006/02/27 12:17:45  brouard
                    911:   (Module): One freematrix added in mlikeli! 0.98c
                    912: 
                    913:   Revision 1.114  2006/02/26 12:57:58  brouard
                    914:   (Module): Some improvements in processing parameter
                    915:   filename with strsep.
                    916: 
                    917:   Revision 1.113  2006/02/24 14:20:24  brouard
                    918:   (Module): Memory leaks checks with valgrind and:
                    919:   datafile was not closed, some imatrix were not freed and on matrix
                    920:   allocation too.
                    921: 
                    922:   Revision 1.112  2006/01/30 09:55:26  brouard
                    923:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    924: 
                    925:   Revision 1.111  2006/01/25 20:38:18  brouard
                    926:   (Module): Lots of cleaning and bugs added (Gompertz)
                    927:   (Module): Comments can be added in data file. Missing date values
                    928:   can be a simple dot '.'.
                    929: 
                    930:   Revision 1.110  2006/01/25 00:51:50  brouard
                    931:   (Module): Lots of cleaning and bugs added (Gompertz)
                    932: 
                    933:   Revision 1.109  2006/01/24 19:37:15  brouard
                    934:   (Module): Comments (lines starting with a #) are allowed in data.
                    935: 
                    936:   Revision 1.108  2006/01/19 18:05:42  lievre
                    937:   Gnuplot problem appeared...
                    938:   To be fixed
                    939: 
                    940:   Revision 1.107  2006/01/19 16:20:37  brouard
                    941:   Test existence of gnuplot in imach path
                    942: 
                    943:   Revision 1.106  2006/01/19 13:24:36  brouard
                    944:   Some cleaning and links added in html output
                    945: 
                    946:   Revision 1.105  2006/01/05 20:23:19  lievre
                    947:   *** empty log message ***
                    948: 
                    949:   Revision 1.104  2005/09/30 16:11:43  lievre
                    950:   (Module): sump fixed, loop imx fixed, and simplifications.
                    951:   (Module): If the status is missing at the last wave but we know
                    952:   that the person is alive, then we can code his/her status as -2
                    953:   (instead of missing=-1 in earlier versions) and his/her
                    954:   contributions to the likelihood is 1 - Prob of dying from last
                    955:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    956:   the healthy state at last known wave). Version is 0.98
                    957: 
                    958:   Revision 1.103  2005/09/30 15:54:49  lievre
                    959:   (Module): sump fixed, loop imx fixed, and simplifications.
                    960: 
                    961:   Revision 1.102  2004/09/15 17:31:30  brouard
                    962:   Add the possibility to read data file including tab characters.
                    963: 
                    964:   Revision 1.101  2004/09/15 10:38:38  brouard
                    965:   Fix on curr_time
                    966: 
                    967:   Revision 1.100  2004/07/12 18:29:06  brouard
                    968:   Add version for Mac OS X. Just define UNIX in Makefile
                    969: 
                    970:   Revision 1.99  2004/06/05 08:57:40  brouard
                    971:   *** empty log message ***
                    972: 
                    973:   Revision 1.98  2004/05/16 15:05:56  brouard
                    974:   New version 0.97 . First attempt to estimate force of mortality
                    975:   directly from the data i.e. without the need of knowing the health
                    976:   state at each age, but using a Gompertz model: log u =a + b*age .
                    977:   This is the basic analysis of mortality and should be done before any
                    978:   other analysis, in order to test if the mortality estimated from the
                    979:   cross-longitudinal survey is different from the mortality estimated
                    980:   from other sources like vital statistic data.
                    981: 
                    982:   The same imach parameter file can be used but the option for mle should be -3.
                    983: 
1.324     brouard   984:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   985:   former routines in order to include the new code within the former code.
                    986: 
                    987:   The output is very simple: only an estimate of the intercept and of
                    988:   the slope with 95% confident intervals.
                    989: 
                    990:   Current limitations:
                    991:   A) Even if you enter covariates, i.e. with the
                    992:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    993:   B) There is no computation of Life Expectancy nor Life Table.
                    994: 
                    995:   Revision 1.97  2004/02/20 13:25:42  lievre
                    996:   Version 0.96d. Population forecasting command line is (temporarily)
                    997:   suppressed.
                    998: 
                    999:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1000:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1001:   rewritten within the same printf. Workaround: many printfs.
                   1002: 
                   1003:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1004:   * imach.c (Repository):
                   1005:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1006:   matrix (cov(a12,c31) instead of numbers.
                   1007: 
                   1008:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1009:   Just cleaning
                   1010: 
                   1011:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1012:   (Module): On windows (cygwin) function asctime_r doesn't
                   1013:   exist so I changed back to asctime which exists.
                   1014:   (Module): Version 0.96b
                   1015: 
                   1016:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1017:   (Module): On windows (cygwin) function asctime_r doesn't
                   1018:   exist so I changed back to asctime which exists.
                   1019: 
                   1020:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1021:   * imach.c (Repository): Duplicated warning errors corrected.
                   1022:   (Repository): Elapsed time after each iteration is now output. It
                   1023:   helps to forecast when convergence will be reached. Elapsed time
                   1024:   is stamped in powell.  We created a new html file for the graphs
                   1025:   concerning matrix of covariance. It has extension -cov.htm.
                   1026: 
                   1027:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1028:   (Module): Some bugs corrected for windows. Also, when
                   1029:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1030:   of the covariance matrix to be input.
                   1031: 
                   1032:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1033:   (Module): Some bugs corrected for windows. Also, when
                   1034:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1035:   of the covariance matrix to be input.
                   1036: 
                   1037:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1038:   * 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.
                   1039: 
                   1040:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1041:   Version 0.96
                   1042: 
                   1043:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1044:   (Module): Change position of html and gnuplot routines and added
                   1045:   routine fileappend.
                   1046: 
                   1047:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1048:   * imach.c (Repository): Check when date of death was earlier that
                   1049:   current date of interview. It may happen when the death was just
                   1050:   prior to the death. In this case, dh was negative and likelihood
                   1051:   was wrong (infinity). We still send an "Error" but patch by
                   1052:   assuming that the date of death was just one stepm after the
                   1053:   interview.
                   1054:   (Repository): Because some people have very long ID (first column)
                   1055:   we changed int to long in num[] and we added a new lvector for
                   1056:   memory allocation. But we also truncated to 8 characters (left
                   1057:   truncation)
                   1058:   (Repository): No more line truncation errors.
                   1059: 
                   1060:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1061:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1062:   place. It differs from routine "prevalence" which may be called
                   1063:   many times. Probs is memory consuming and must be used with
                   1064:   parcimony.
                   1065:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1066: 
                   1067:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1068:   *** empty log message ***
                   1069: 
                   1070:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1071:   Add log in  imach.c and  fullversion number is now printed.
                   1072: 
                   1073: */
                   1074: /*
                   1075:    Interpolated Markov Chain
                   1076: 
                   1077:   Short summary of the programme:
                   1078:   
1.227     brouard  1079:   This program computes Healthy Life Expectancies or State-specific
                   1080:   (if states aren't health statuses) Expectancies from
                   1081:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1082: 
                   1083:   -1- a first survey ("cross") where individuals from different ages
                   1084:   are interviewed on their health status or degree of disability (in
                   1085:   the case of a health survey which is our main interest)
                   1086: 
                   1087:   -2- at least a second wave of interviews ("longitudinal") which
                   1088:   measure each change (if any) in individual health status.  Health
                   1089:   expectancies are computed from the time spent in each health state
                   1090:   according to a model. More health states you consider, more time is
                   1091:   necessary to reach the Maximum Likelihood of the parameters involved
                   1092:   in the model.  The simplest model is the multinomial logistic model
                   1093:   where pij is the probability to be observed in state j at the second
                   1094:   wave conditional to be observed in state i at the first
                   1095:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1096:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1097:   have a more complex model than "constant and age", you should modify
                   1098:   the program where the markup *Covariates have to be included here
                   1099:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1100:   convergence.
                   1101: 
                   1102:   The advantage of this computer programme, compared to a simple
                   1103:   multinomial logistic model, is clear when the delay between waves is not
                   1104:   identical for each individual. Also, if a individual missed an
                   1105:   intermediate interview, the information is lost, but taken into
                   1106:   account using an interpolation or extrapolation.  
                   1107: 
                   1108:   hPijx is the probability to be observed in state i at age x+h
                   1109:   conditional to the observed state i at age x. The delay 'h' can be
                   1110:   split into an exact number (nh*stepm) of unobserved intermediate
                   1111:   states. This elementary transition (by month, quarter,
                   1112:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1113:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1114:   and the contribution of each individual to the likelihood is simply
                   1115:   hPijx.
                   1116: 
                   1117:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1118:   of the life expectancies. It also computes the period (stable) prevalence.
                   1119: 
                   1120: Back prevalence and projections:
1.227     brouard  1121: 
                   1122:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1123:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1124:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1125:    mobilavproj)
                   1126: 
                   1127:     Computes the back prevalence limit for any combination of
                   1128:     covariate values k at any age between ageminpar and agemaxpar and
                   1129:     returns it in **bprlim. In the loops,
                   1130: 
                   1131:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1132:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1133: 
                   1134:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1135:    Computes for any combination of covariates k and any age between bage and fage 
                   1136:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1137:                        oldm=oldms;savm=savms;
1.227     brouard  1138: 
1.267     brouard  1139:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1140:      Computes the transition matrix starting at age 'age' over
                   1141:      'nhstepm*hstepm*stepm' months (i.e. until
                   1142:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1143:      nhstepm*hstepm matrices. 
                   1144: 
                   1145:      Returns p3mat[i][j][h] after calling
                   1146:      p3mat[i][j][h]=matprod2(newm,
                   1147:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1148:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1149:      oldm);
1.226     brouard  1150: 
                   1151: Important routines
                   1152: 
                   1153: - func (or funcone), computes logit (pij) distinguishing
                   1154:   o fixed variables (single or product dummies or quantitative);
                   1155:   o varying variables by:
                   1156:    (1) wave (single, product dummies, quantitative), 
                   1157:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1158:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1159:        % varying dummy (not done) or quantitative (not done);
                   1160: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1161:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1162: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1163:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1164:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1165: 
1.226     brouard  1166: 
                   1167:   
1.324     brouard  1168:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1169:            Institut national d'études démographiques, Paris.
1.126     brouard  1170:   This software have been partly granted by Euro-REVES, a concerted action
                   1171:   from the European Union.
                   1172:   It is copyrighted identically to a GNU software product, ie programme and
                   1173:   software can be distributed freely for non commercial use. Latest version
                   1174:   can be accessed at http://euroreves.ined.fr/imach .
                   1175: 
                   1176:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1177:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1178:   
                   1179:   **********************************************************************/
                   1180: /*
                   1181:   main
                   1182:   read parameterfile
                   1183:   read datafile
                   1184:   concatwav
                   1185:   freqsummary
                   1186:   if (mle >= 1)
                   1187:     mlikeli
                   1188:   print results files
                   1189:   if mle==1 
                   1190:      computes hessian
                   1191:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1192:       begin-prev-date,...
                   1193:   open gnuplot file
                   1194:   open html file
1.145     brouard  1195:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1196:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1197:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1198:     freexexit2 possible for memory heap.
                   1199: 
                   1200:   h Pij x                         | pij_nom  ficrestpij
                   1201:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1202:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1203:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1204: 
                   1205:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1206:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1207:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1208:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1209:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1210: 
1.126     brouard  1211:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1212:   health expectancies
                   1213:   Variance-covariance of DFLE
                   1214:   prevalence()
                   1215:    movingaverage()
                   1216:   varevsij() 
                   1217:   if popbased==1 varevsij(,popbased)
                   1218:   total life expectancies
                   1219:   Variance of period (stable) prevalence
                   1220:  end
                   1221: */
                   1222: 
1.187     brouard  1223: /* #define DEBUG */
                   1224: /* #define DEBUGBRENT */
1.203     brouard  1225: /* #define DEBUGLINMIN */
                   1226: /* #define DEBUGHESS */
                   1227: #define DEBUGHESSIJ
1.224     brouard  1228: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1229: #define POWELL /* Instead of NLOPT */
1.224     brouard  1230: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1231: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1232: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1233: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1234: 
                   1235: #include <math.h>
                   1236: #include <stdio.h>
                   1237: #include <stdlib.h>
                   1238: #include <string.h>
1.226     brouard  1239: #include <ctype.h>
1.159     brouard  1240: 
                   1241: #ifdef _WIN32
                   1242: #include <io.h>
1.172     brouard  1243: #include <windows.h>
                   1244: #include <tchar.h>
1.159     brouard  1245: #else
1.126     brouard  1246: #include <unistd.h>
1.159     brouard  1247: #endif
1.126     brouard  1248: 
                   1249: #include <limits.h>
                   1250: #include <sys/types.h>
1.171     brouard  1251: 
                   1252: #if defined(__GNUC__)
                   1253: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1254: #endif
                   1255: 
1.126     brouard  1256: #include <sys/stat.h>
                   1257: #include <errno.h>
1.159     brouard  1258: /* extern int errno; */
1.126     brouard  1259: 
1.157     brouard  1260: /* #ifdef LINUX */
                   1261: /* #include <time.h> */
                   1262: /* #include "timeval.h" */
                   1263: /* #else */
                   1264: /* #include <sys/time.h> */
                   1265: /* #endif */
                   1266: 
1.126     brouard  1267: #include <time.h>
                   1268: 
1.136     brouard  1269: #ifdef GSL
                   1270: #include <gsl/gsl_errno.h>
                   1271: #include <gsl/gsl_multimin.h>
                   1272: #endif
                   1273: 
1.167     brouard  1274: 
1.162     brouard  1275: #ifdef NLOPT
                   1276: #include <nlopt.h>
                   1277: typedef struct {
                   1278:   double (* function)(double [] );
                   1279: } myfunc_data ;
                   1280: #endif
                   1281: 
1.126     brouard  1282: /* #include <libintl.h> */
                   1283: /* #define _(String) gettext (String) */
                   1284: 
1.251     brouard  1285: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1286: 
                   1287: #define GNUPLOTPROGRAM "gnuplot"
                   1288: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1289: #define FILENAMELENGTH 256
1.126     brouard  1290: 
                   1291: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1292: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1293: 
1.144     brouard  1294: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1295: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1296: 
                   1297: #define NINTERVMAX 8
1.144     brouard  1298: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1299: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1300: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1301: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1302: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1303: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1304: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1305: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1306: /* #define AGESUP 130 */
1.288     brouard  1307: /* #define AGESUP 150 */
                   1308: #define AGESUP 200
1.268     brouard  1309: #define AGEINF 0
1.218     brouard  1310: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1311: #define AGEBASE 40
1.194     brouard  1312: #define AGEOVERFLOW 1.e20
1.164     brouard  1313: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1314: #ifdef _WIN32
                   1315: #define DIRSEPARATOR '\\'
                   1316: #define CHARSEPARATOR "\\"
                   1317: #define ODIRSEPARATOR '/'
                   1318: #else
1.126     brouard  1319: #define DIRSEPARATOR '/'
                   1320: #define CHARSEPARATOR "/"
                   1321: #define ODIRSEPARATOR '\\'
                   1322: #endif
                   1323: 
1.342   ! brouard  1324: /* $Id: imach.c,v 1.341 2022/09/11 07:58:42 brouard Exp $ */
1.126     brouard  1325: /* $State: Exp $ */
1.196     brouard  1326: #include "version.h"
                   1327: char version[]=__IMACH_VERSION__;
1.337     brouard  1328: 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.342   ! brouard  1329: char fullversion[]="$Revision: 1.341 $ $Date: 2022/09/11 07:58:42 $"; 
1.126     brouard  1330: char strstart[80];
                   1331: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1332: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342   ! brouard  1333: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1334: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1335: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1336: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1337: 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  1338: 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  1339: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1340: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1341: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1342: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1343: 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  1344: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1345: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1346: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1347: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1348: int nsd=0; /**< Total number of single dummy variables (output) */
                   1349: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1350: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1351: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1352: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1353: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1354: int cptcov=0; /* Working variable */
1.334     brouard  1355: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1356: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1357: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1358: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1359: int nlstate=2; /* Number of live states */
                   1360: int ndeath=1; /* Number of dead states */
1.130     brouard  1361: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1362: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1363: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1364: int popbased=0;
                   1365: 
                   1366: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1367: int maxwav=0; /* Maxim number of waves */
                   1368: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1369: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1370: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1371:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1372: int mle=1, weightopt=0;
1.126     brouard  1373: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1374: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1375: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1376:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1377: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1378: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1379: 
1.130     brouard  1380: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1381: double **matprod2(); /* test */
1.126     brouard  1382: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1383: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1384: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1385: 
1.136     brouard  1386: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1387: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1388: FILE *ficlog, *ficrespow;
1.130     brouard  1389: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1390: double fretone; /* Only one call to likelihood */
1.130     brouard  1391: long ipmx=0; /* Number of contributions */
1.126     brouard  1392: double sw; /* Sum of weights */
                   1393: char filerespow[FILENAMELENGTH];
                   1394: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1395: FILE *ficresilk;
                   1396: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1397: FILE *ficresprobmorprev;
                   1398: FILE *fichtm, *fichtmcov; /* Html File */
                   1399: FILE *ficreseij;
                   1400: char filerese[FILENAMELENGTH];
                   1401: FILE *ficresstdeij;
                   1402: char fileresstde[FILENAMELENGTH];
                   1403: FILE *ficrescveij;
                   1404: char filerescve[FILENAMELENGTH];
                   1405: FILE  *ficresvij;
                   1406: char fileresv[FILENAMELENGTH];
1.269     brouard  1407: 
1.126     brouard  1408: char title[MAXLINE];
1.234     brouard  1409: char model[MAXLINE]; /**< The model line */
1.217     brouard  1410: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1411: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1412: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1413: char command[FILENAMELENGTH];
                   1414: int  outcmd=0;
                   1415: 
1.217     brouard  1416: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1417: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1418: char filelog[FILENAMELENGTH]; /* Log file */
                   1419: char filerest[FILENAMELENGTH];
                   1420: char fileregp[FILENAMELENGTH];
                   1421: char popfile[FILENAMELENGTH];
                   1422: 
                   1423: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1424: 
1.157     brouard  1425: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1426: /* struct timezone tzp; */
                   1427: /* extern int gettimeofday(); */
                   1428: struct tm tml, *gmtime(), *localtime();
                   1429: 
                   1430: extern time_t time();
                   1431: 
                   1432: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1433: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1434: struct tm tm;
                   1435: 
1.126     brouard  1436: char strcurr[80], strfor[80];
                   1437: 
                   1438: char *endptr;
                   1439: long lval;
                   1440: double dval;
                   1441: 
                   1442: #define NR_END 1
                   1443: #define FREE_ARG char*
                   1444: #define FTOL 1.0e-10
                   1445: 
                   1446: #define NRANSI 
1.240     brouard  1447: #define ITMAX 200
                   1448: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1449: 
                   1450: #define TOL 2.0e-4 
                   1451: 
                   1452: #define CGOLD 0.3819660 
                   1453: #define ZEPS 1.0e-10 
                   1454: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1455: 
                   1456: #define GOLD 1.618034 
                   1457: #define GLIMIT 100.0 
                   1458: #define TINY 1.0e-20 
                   1459: 
                   1460: static double maxarg1,maxarg2;
                   1461: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1462: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1463:   
                   1464: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1465: #define rint(a) floor(a+0.5)
1.166     brouard  1466: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1467: #define mytinydouble 1.0e-16
1.166     brouard  1468: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1469: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1470: /* static double dsqrarg; */
                   1471: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1472: static double sqrarg;
                   1473: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1474: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1475: int agegomp= AGEGOMP;
                   1476: 
                   1477: int imx; 
                   1478: int stepm=1;
                   1479: /* Stepm, step in month: minimum step interpolation*/
                   1480: 
                   1481: int estepm;
                   1482: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1483: 
                   1484: int m,nb;
                   1485: long *num;
1.197     brouard  1486: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1487: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1488:                   covariate for which somebody answered excluding 
                   1489:                   undefined. Usually 2: 0 and 1. */
                   1490: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1491:                             covariate for which somebody answered including 
                   1492:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1493: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1494: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1495: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1496: 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  1497: double *ageexmed,*agecens;
                   1498: double dateintmean=0;
1.296     brouard  1499:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1500:   double anprojf, mprojf, jprojf;
1.126     brouard  1501: 
1.296     brouard  1502:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1503:   double anbackf, mbackf, jbackf;
                   1504:   double jintmean,mintmean,aintmean;  
1.126     brouard  1505: double *weight;
                   1506: int **s; /* Status */
1.141     brouard  1507: double *agedc;
1.145     brouard  1508: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1509:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1510:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1511: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1512: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1513: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1514: double  idx; 
                   1515: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1516: /* Some documentation */
                   1517:       /*   Design original data
                   1518:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1519:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1520:        *                                                             ntv=3     nqtv=1
1.330     brouard  1521:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1522:        * For time varying covariate, quanti or dummies
                   1523:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1524:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1525:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1526:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1527:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1528:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1529:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1530:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1531:        */
                   1532: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1533: /* 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
                   1534:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1535:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1536: */
1.319     brouard  1537: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1538: /*    k        1  2   3   4     5    6    7     8    9 */
                   1539: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1540:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1541:                                                          /* product */
                   1542: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1543:                                                          /*(single or product without age), 2 dummy*/
                   1544:                                                          /* with age product, 3 quant with age product*/
                   1545: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1546: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1547: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1548: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1549: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1550: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1551: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1552: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1553: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1554: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1555: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1556: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1557: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1558: /* 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  1559: /* 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  1560: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1561: /* Type                    */
                   1562: /* V         1  2  3  4  5 */
                   1563: /*           F  F  V  V  V */
                   1564: /*           D  Q  D  D  Q */
                   1565: /*                         */
                   1566: int *TvarsD;
1.330     brouard  1567: int *TnsdVar;
1.234     brouard  1568: int *TvarsDind;
                   1569: int *TvarsQ;
                   1570: int *TvarsQind;
                   1571: 
1.318     brouard  1572: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1573: int nresult=0;
1.258     brouard  1574: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1575: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1576: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1577: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1578: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1579: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1580: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1581: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1582: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1583: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1584: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1585: 
                   1586: /* 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
                   1587:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1588:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1589: */
1.234     brouard  1590: /* 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  1591: 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 */
                   1592: 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 */
                   1593: 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 */
                   1594: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1595: 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 */
                   1596: 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  1597: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1598: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1599: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1600: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1601: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1602: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1603: 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 */
                   1604: 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  1605: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1606: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1607:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1608:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1609:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1610:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1611:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1612: int *Tvarsel; /**< Selected covariates for output */
                   1613: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1614: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1615: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1616: 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  1617: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1618: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1619: int *Tage;
1.227     brouard  1620: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1621: 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  1622: 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*/ 
                   1623: 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  1624: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1625: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1626: int **Tvard;
1.330     brouard  1627: int **Tvardk;
1.227     brouard  1628: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1629: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1630: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1631:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1632:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1633: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1634: double *lsurv, *lpop, *tpop;
                   1635: 
1.231     brouard  1636: #define FD 1; /* Fixed dummy covariate */
                   1637: #define FQ 2; /* Fixed quantitative covariate */
                   1638: #define FP 3; /* Fixed product covariate */
                   1639: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1640: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1641: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1642: #define VD 10; /* Varying dummy covariate */
                   1643: #define VQ 11; /* Varying quantitative covariate */
                   1644: #define VP 12; /* Varying product covariate */
                   1645: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1646: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1647: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1648: #define APFD 16; /* Age product * fixed dummy covariate */
                   1649: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1650: #define APVD 18; /* Age product * varying dummy covariate */
                   1651: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1652: 
                   1653: #define FTYPE 1; /* Fixed covariate */
                   1654: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1655: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1656: 
                   1657: struct kmodel{
                   1658:        int maintype; /* main type */
                   1659:        int subtype; /* subtype */
                   1660: };
                   1661: struct kmodel modell[NCOVMAX];
                   1662: 
1.143     brouard  1663: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1664: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1665: 
                   1666: /**************** split *************************/
                   1667: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1668: {
                   1669:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1670:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1671:   */ 
                   1672:   char *ss;                            /* pointer */
1.186     brouard  1673:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1674: 
                   1675:   l1 = strlen(path );                  /* length of path */
                   1676:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1677:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1678:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1679:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1680:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1681:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1682:     /* get current working directory */
                   1683:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1684: #ifdef WIN32
                   1685:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1686: #else
                   1687:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1688: #endif
1.126     brouard  1689:       return( GLOCK_ERROR_GETCWD );
                   1690:     }
                   1691:     /* got dirc from getcwd*/
                   1692:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1693:   } else {                             /* strip directory from path */
1.126     brouard  1694:     ss++;                              /* after this, the filename */
                   1695:     l2 = strlen( ss );                 /* length of filename */
                   1696:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1697:     strcpy( name, ss );                /* save file name */
                   1698:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1699:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1700:     printf(" DIRC2 = %s \n",dirc);
                   1701:   }
                   1702:   /* We add a separator at the end of dirc if not exists */
                   1703:   l1 = strlen( dirc );                 /* length of directory */
                   1704:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1705:     dirc[l1] =  DIRSEPARATOR;
                   1706:     dirc[l1+1] = 0; 
                   1707:     printf(" DIRC3 = %s \n",dirc);
                   1708:   }
                   1709:   ss = strrchr( name, '.' );           /* find last / */
                   1710:   if (ss >0){
                   1711:     ss++;
                   1712:     strcpy(ext,ss);                    /* save extension */
                   1713:     l1= strlen( name);
                   1714:     l2= strlen(ss)+1;
                   1715:     strncpy( finame, name, l1-l2);
                   1716:     finame[l1-l2]= 0;
                   1717:   }
                   1718: 
                   1719:   return( 0 );                         /* we're done */
                   1720: }
                   1721: 
                   1722: 
                   1723: /******************************************/
                   1724: 
                   1725: void replace_back_to_slash(char *s, char*t)
                   1726: {
                   1727:   int i;
                   1728:   int lg=0;
                   1729:   i=0;
                   1730:   lg=strlen(t);
                   1731:   for(i=0; i<= lg; i++) {
                   1732:     (s[i] = t[i]);
                   1733:     if (t[i]== '\\') s[i]='/';
                   1734:   }
                   1735: }
                   1736: 
1.132     brouard  1737: char *trimbb(char *out, char *in)
1.137     brouard  1738: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1739:   char *s;
                   1740:   s=out;
                   1741:   while (*in != '\0'){
1.137     brouard  1742:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1743:       in++;
                   1744:     }
                   1745:     *out++ = *in++;
                   1746:   }
                   1747:   *out='\0';
                   1748:   return s;
                   1749: }
                   1750: 
1.187     brouard  1751: /* char *substrchaine(char *out, char *in, char *chain) */
                   1752: /* { */
                   1753: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1754: /*   char *s, *t; */
                   1755: /*   t=in;s=out; */
                   1756: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1757: /*     *out++ = *in++; */
                   1758: /*   } */
                   1759: 
                   1760: /*   /\* *in matches *chain *\/ */
                   1761: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1762: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1763: /*   } */
                   1764: /*   in--; chain--; */
                   1765: /*   while ( (*in != '\0')){ */
                   1766: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1767: /*     *out++ = *in++; */
                   1768: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1769: /*   } */
                   1770: /*   *out='\0'; */
                   1771: /*   out=s; */
                   1772: /*   return out; */
                   1773: /* } */
                   1774: char *substrchaine(char *out, char *in, char *chain)
                   1775: {
                   1776:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1777:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1778: 
                   1779:   char *strloc;
                   1780: 
                   1781:   strcpy (out, in); 
                   1782:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1783:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1784:   if(strloc != NULL){ 
                   1785:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1786:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1787:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1788:   }
                   1789:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1790:   return out;
                   1791: }
                   1792: 
                   1793: 
1.145     brouard  1794: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1795: {
1.187     brouard  1796:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1797:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1798:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1799:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1800:   */
1.160     brouard  1801:   char *s, *t;
1.145     brouard  1802:   t=in;s=in;
                   1803:   while ((*in != occ) && (*in != '\0')){
                   1804:     *alocc++ = *in++;
                   1805:   }
                   1806:   if( *in == occ){
                   1807:     *(alocc)='\0';
                   1808:     s=++in;
                   1809:   }
                   1810:  
                   1811:   if (s == t) {/* occ not found */
                   1812:     *(alocc-(in-s))='\0';
                   1813:     in=s;
                   1814:   }
                   1815:   while ( *in != '\0'){
                   1816:     *blocc++ = *in++;
                   1817:   }
                   1818: 
                   1819:   *blocc='\0';
                   1820:   return t;
                   1821: }
1.137     brouard  1822: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1823: {
1.187     brouard  1824:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1825:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1826:      gives blocc="abcdef2ghi" and alocc="j".
                   1827:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1828:   */
                   1829:   char *s, *t;
                   1830:   t=in;s=in;
                   1831:   while (*in != '\0'){
                   1832:     while( *in == occ){
                   1833:       *blocc++ = *in++;
                   1834:       s=in;
                   1835:     }
                   1836:     *blocc++ = *in++;
                   1837:   }
                   1838:   if (s == t) /* occ not found */
                   1839:     *(blocc-(in-s))='\0';
                   1840:   else
                   1841:     *(blocc-(in-s)-1)='\0';
                   1842:   in=s;
                   1843:   while ( *in != '\0'){
                   1844:     *alocc++ = *in++;
                   1845:   }
                   1846: 
                   1847:   *alocc='\0';
                   1848:   return s;
                   1849: }
                   1850: 
1.126     brouard  1851: int nbocc(char *s, char occ)
                   1852: {
                   1853:   int i,j=0;
                   1854:   int lg=20;
                   1855:   i=0;
                   1856:   lg=strlen(s);
                   1857:   for(i=0; i<= lg; i++) {
1.234     brouard  1858:     if  (s[i] == occ ) j++;
1.126     brouard  1859:   }
                   1860:   return j;
                   1861: }
                   1862: 
1.137     brouard  1863: /* void cutv(char *u,char *v, char*t, char occ) */
                   1864: /* { */
                   1865: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1866: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1867: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1868: /*   int i,lg,j,p=0; */
                   1869: /*   i=0; */
                   1870: /*   lg=strlen(t); */
                   1871: /*   for(j=0; j<=lg-1; j++) { */
                   1872: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1873: /*   } */
1.126     brouard  1874: 
1.137     brouard  1875: /*   for(j=0; j<p; j++) { */
                   1876: /*     (u[j] = t[j]); */
                   1877: /*   } */
                   1878: /*      u[p]='\0'; */
1.126     brouard  1879: 
1.137     brouard  1880: /*    for(j=0; j<= lg; j++) { */
                   1881: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1882: /*   } */
                   1883: /* } */
1.126     brouard  1884: 
1.160     brouard  1885: #ifdef _WIN32
                   1886: char * strsep(char **pp, const char *delim)
                   1887: {
                   1888:   char *p, *q;
                   1889:          
                   1890:   if ((p = *pp) == NULL)
                   1891:     return 0;
                   1892:   if ((q = strpbrk (p, delim)) != NULL)
                   1893:   {
                   1894:     *pp = q + 1;
                   1895:     *q = '\0';
                   1896:   }
                   1897:   else
                   1898:     *pp = 0;
                   1899:   return p;
                   1900: }
                   1901: #endif
                   1902: 
1.126     brouard  1903: /********************** nrerror ********************/
                   1904: 
                   1905: void nrerror(char error_text[])
                   1906: {
                   1907:   fprintf(stderr,"ERREUR ...\n");
                   1908:   fprintf(stderr,"%s\n",error_text);
                   1909:   exit(EXIT_FAILURE);
                   1910: }
                   1911: /*********************** vector *******************/
                   1912: double *vector(int nl, int nh)
                   1913: {
                   1914:   double *v;
                   1915:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1916:   if (!v) nrerror("allocation failure in vector");
                   1917:   return v-nl+NR_END;
                   1918: }
                   1919: 
                   1920: /************************ free vector ******************/
                   1921: void free_vector(double*v, int nl, int nh)
                   1922: {
                   1923:   free((FREE_ARG)(v+nl-NR_END));
                   1924: }
                   1925: 
                   1926: /************************ivector *******************************/
                   1927: int *ivector(long nl,long nh)
                   1928: {
                   1929:   int *v;
                   1930:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1931:   if (!v) nrerror("allocation failure in ivector");
                   1932:   return v-nl+NR_END;
                   1933: }
                   1934: 
                   1935: /******************free ivector **************************/
                   1936: void free_ivector(int *v, long nl, long nh)
                   1937: {
                   1938:   free((FREE_ARG)(v+nl-NR_END));
                   1939: }
                   1940: 
                   1941: /************************lvector *******************************/
                   1942: long *lvector(long nl,long nh)
                   1943: {
                   1944:   long *v;
                   1945:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1946:   if (!v) nrerror("allocation failure in ivector");
                   1947:   return v-nl+NR_END;
                   1948: }
                   1949: 
                   1950: /******************free lvector **************************/
                   1951: void free_lvector(long *v, long nl, long nh)
                   1952: {
                   1953:   free((FREE_ARG)(v+nl-NR_END));
                   1954: }
                   1955: 
                   1956: /******************* imatrix *******************************/
                   1957: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1958:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1959: { 
                   1960:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1961:   int **m; 
                   1962:   
                   1963:   /* allocate pointers to rows */ 
                   1964:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1965:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1966:   m += NR_END; 
                   1967:   m -= nrl; 
                   1968:   
                   1969:   
                   1970:   /* allocate rows and set pointers to them */ 
                   1971:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1972:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1973:   m[nrl] += NR_END; 
                   1974:   m[nrl] -= ncl; 
                   1975:   
                   1976:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1977:   
                   1978:   /* return pointer to array of pointers to rows */ 
                   1979:   return m; 
                   1980: } 
                   1981: 
                   1982: /****************** free_imatrix *************************/
                   1983: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1984:       int **m;
                   1985:       long nch,ncl,nrh,nrl; 
                   1986:      /* free an int matrix allocated by imatrix() */ 
                   1987: { 
                   1988:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1989:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1990: } 
                   1991: 
                   1992: /******************* matrix *******************************/
                   1993: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1994: {
                   1995:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1996:   double **m;
                   1997: 
                   1998:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1999:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2000:   m += NR_END;
                   2001:   m -= nrl;
                   2002: 
                   2003:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2004:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2005:   m[nrl] += NR_END;
                   2006:   m[nrl] -= ncl;
                   2007: 
                   2008:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2009:   return m;
1.145     brouard  2010:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2011: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2012: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2013:    */
                   2014: }
                   2015: 
                   2016: /*************************free matrix ************************/
                   2017: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2018: {
                   2019:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2020:   free((FREE_ARG)(m+nrl-NR_END));
                   2021: }
                   2022: 
                   2023: /******************* ma3x *******************************/
                   2024: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2025: {
                   2026:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2027:   double ***m;
                   2028: 
                   2029:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2030:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2031:   m += NR_END;
                   2032:   m -= nrl;
                   2033: 
                   2034:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2035:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2036:   m[nrl] += NR_END;
                   2037:   m[nrl] -= ncl;
                   2038: 
                   2039:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2040: 
                   2041:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2042:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2043:   m[nrl][ncl] += NR_END;
                   2044:   m[nrl][ncl] -= nll;
                   2045:   for (j=ncl+1; j<=nch; j++) 
                   2046:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2047:   
                   2048:   for (i=nrl+1; i<=nrh; i++) {
                   2049:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2050:     for (j=ncl+1; j<=nch; j++) 
                   2051:       m[i][j]=m[i][j-1]+nlay;
                   2052:   }
                   2053:   return m; 
                   2054:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2055:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2056:   */
                   2057: }
                   2058: 
                   2059: /*************************free ma3x ************************/
                   2060: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2061: {
                   2062:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2063:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2064:   free((FREE_ARG)(m+nrl-NR_END));
                   2065: }
                   2066: 
                   2067: /*************** function subdirf ***********/
                   2068: char *subdirf(char fileres[])
                   2069: {
                   2070:   /* Caution optionfilefiname is hidden */
                   2071:   strcpy(tmpout,optionfilefiname);
                   2072:   strcat(tmpout,"/"); /* Add to the right */
                   2073:   strcat(tmpout,fileres);
                   2074:   return tmpout;
                   2075: }
                   2076: 
                   2077: /*************** function subdirf2 ***********/
                   2078: char *subdirf2(char fileres[], char *preop)
                   2079: {
1.314     brouard  2080:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2081:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2082:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2083:   /* Caution optionfilefiname is hidden */
                   2084:   strcpy(tmpout,optionfilefiname);
                   2085:   strcat(tmpout,"/");
                   2086:   strcat(tmpout,preop);
                   2087:   strcat(tmpout,fileres);
                   2088:   return tmpout;
                   2089: }
                   2090: 
                   2091: /*************** function subdirf3 ***********/
                   2092: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2093: {
                   2094:   
                   2095:   /* Caution optionfilefiname is hidden */
                   2096:   strcpy(tmpout,optionfilefiname);
                   2097:   strcat(tmpout,"/");
                   2098:   strcat(tmpout,preop);
                   2099:   strcat(tmpout,preop2);
                   2100:   strcat(tmpout,fileres);
                   2101:   return tmpout;
                   2102: }
1.213     brouard  2103:  
                   2104: /*************** function subdirfext ***********/
                   2105: char *subdirfext(char fileres[], char *preop, char *postop)
                   2106: {
                   2107:   
                   2108:   strcpy(tmpout,preop);
                   2109:   strcat(tmpout,fileres);
                   2110:   strcat(tmpout,postop);
                   2111:   return tmpout;
                   2112: }
1.126     brouard  2113: 
1.213     brouard  2114: /*************** function subdirfext3 ***********/
                   2115: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2116: {
                   2117:   
                   2118:   /* Caution optionfilefiname is hidden */
                   2119:   strcpy(tmpout,optionfilefiname);
                   2120:   strcat(tmpout,"/");
                   2121:   strcat(tmpout,preop);
                   2122:   strcat(tmpout,fileres);
                   2123:   strcat(tmpout,postop);
                   2124:   return tmpout;
                   2125: }
                   2126:  
1.162     brouard  2127: char *asc_diff_time(long time_sec, char ascdiff[])
                   2128: {
                   2129:   long sec_left, days, hours, minutes;
                   2130:   days = (time_sec) / (60*60*24);
                   2131:   sec_left = (time_sec) % (60*60*24);
                   2132:   hours = (sec_left) / (60*60) ;
                   2133:   sec_left = (sec_left) %(60*60);
                   2134:   minutes = (sec_left) /60;
                   2135:   sec_left = (sec_left) % (60);
                   2136:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2137:   return ascdiff;
                   2138: }
                   2139: 
1.126     brouard  2140: /***************** f1dim *************************/
                   2141: extern int ncom; 
                   2142: extern double *pcom,*xicom;
                   2143: extern double (*nrfunc)(double []); 
                   2144:  
                   2145: double f1dim(double x) 
                   2146: { 
                   2147:   int j; 
                   2148:   double f;
                   2149:   double *xt; 
                   2150:  
                   2151:   xt=vector(1,ncom); 
                   2152:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2153:   f=(*nrfunc)(xt); 
                   2154:   free_vector(xt,1,ncom); 
                   2155:   return f; 
                   2156: } 
                   2157: 
                   2158: /*****************brent *************************/
                   2159: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2160: {
                   2161:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2162:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2163:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2164:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2165:    * returned function value. 
                   2166:   */
1.126     brouard  2167:   int iter; 
                   2168:   double a,b,d,etemp;
1.159     brouard  2169:   double fu=0,fv,fw,fx;
1.164     brouard  2170:   double ftemp=0.;
1.126     brouard  2171:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2172:   double e=0.0; 
                   2173:  
                   2174:   a=(ax < cx ? ax : cx); 
                   2175:   b=(ax > cx ? ax : cx); 
                   2176:   x=w=v=bx; 
                   2177:   fw=fv=fx=(*f)(x); 
                   2178:   for (iter=1;iter<=ITMAX;iter++) { 
                   2179:     xm=0.5*(a+b); 
                   2180:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2181:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2182:     printf(".");fflush(stdout);
                   2183:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2184: #ifdef DEBUGBRENT
1.126     brouard  2185:     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);
                   2186:     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);
                   2187:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2188: #endif
                   2189:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2190:       *xmin=x; 
                   2191:       return fx; 
                   2192:     } 
                   2193:     ftemp=fu;
                   2194:     if (fabs(e) > tol1) { 
                   2195:       r=(x-w)*(fx-fv); 
                   2196:       q=(x-v)*(fx-fw); 
                   2197:       p=(x-v)*q-(x-w)*r; 
                   2198:       q=2.0*(q-r); 
                   2199:       if (q > 0.0) p = -p; 
                   2200:       q=fabs(q); 
                   2201:       etemp=e; 
                   2202:       e=d; 
                   2203:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2204:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2205:       else { 
1.224     brouard  2206:                                d=p/q; 
                   2207:                                u=x+d; 
                   2208:                                if (u-a < tol2 || b-u < tol2) 
                   2209:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2210:       } 
                   2211:     } else { 
                   2212:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2213:     } 
                   2214:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2215:     fu=(*f)(u); 
                   2216:     if (fu <= fx) { 
                   2217:       if (u >= x) a=x; else b=x; 
                   2218:       SHFT(v,w,x,u) 
1.183     brouard  2219:       SHFT(fv,fw,fx,fu) 
                   2220:     } else { 
                   2221:       if (u < x) a=u; else b=u; 
                   2222:       if (fu <= fw || w == x) { 
1.224     brouard  2223:                                v=w; 
                   2224:                                w=u; 
                   2225:                                fv=fw; 
                   2226:                                fw=fu; 
1.183     brouard  2227:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2228:                                v=u; 
                   2229:                                fv=fu; 
1.183     brouard  2230:       } 
                   2231:     } 
1.126     brouard  2232:   } 
                   2233:   nrerror("Too many iterations in brent"); 
                   2234:   *xmin=x; 
                   2235:   return fx; 
                   2236: } 
                   2237: 
                   2238: /****************** mnbrak ***********************/
                   2239: 
                   2240: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2241:            double (*func)(double)) 
1.183     brouard  2242: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2243: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2244: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2245: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2246:    */
1.126     brouard  2247:   double ulim,u,r,q, dum;
                   2248:   double fu; 
1.187     brouard  2249: 
                   2250:   double scale=10.;
                   2251:   int iterscale=0;
                   2252: 
                   2253:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2254:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2255: 
                   2256: 
                   2257:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2258:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2259:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2260:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2261:   /* } */
                   2262: 
1.126     brouard  2263:   if (*fb > *fa) { 
                   2264:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2265:     SHFT(dum,*fb,*fa,dum) 
                   2266:   } 
1.126     brouard  2267:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2268:   *fc=(*func)(*cx); 
1.183     brouard  2269: #ifdef DEBUG
1.224     brouard  2270:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2271:   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  2272: #endif
1.224     brouard  2273:   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  2274:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2275:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2276:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2277:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2278:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2279:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2280:       fu=(*func)(u); 
1.163     brouard  2281: #ifdef DEBUG
                   2282:       /* f(x)=A(x-u)**2+f(u) */
                   2283:       double A, fparabu; 
                   2284:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2285:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2286:       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);
                   2287:       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  2288:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2289:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2290:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2291:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2292: #endif 
1.184     brouard  2293: #ifdef MNBRAKORIGINAL
1.183     brouard  2294: #else
1.191     brouard  2295: /*       if (fu > *fc) { */
                   2296: /* #ifdef DEBUG */
                   2297: /*       printf("mnbrak4  fu > fc \n"); */
                   2298: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2299: /* #endif */
                   2300: /*     /\* 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 *\\/  *\/ */
                   2301: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2302: /*     dum=u; /\* Shifting c and u *\/ */
                   2303: /*     u = *cx; */
                   2304: /*     *cx = dum; */
                   2305: /*     dum = fu; */
                   2306: /*     fu = *fc; */
                   2307: /*     *fc =dum; */
                   2308: /*       } else { /\* end *\/ */
                   2309: /* #ifdef DEBUG */
                   2310: /*       printf("mnbrak3  fu < fc \n"); */
                   2311: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2312: /* #endif */
                   2313: /*     dum=u; /\* Shifting c and u *\/ */
                   2314: /*     u = *cx; */
                   2315: /*     *cx = dum; */
                   2316: /*     dum = fu; */
                   2317: /*     fu = *fc; */
                   2318: /*     *fc =dum; */
                   2319: /*       } */
1.224     brouard  2320: #ifdef DEBUGMNBRAK
                   2321:                 double A, fparabu; 
                   2322:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2323:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2324:      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);
                   2325:      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  2326: #endif
1.191     brouard  2327:       dum=u; /* Shifting c and u */
                   2328:       u = *cx;
                   2329:       *cx = dum;
                   2330:       dum = fu;
                   2331:       fu = *fc;
                   2332:       *fc =dum;
1.183     brouard  2333: #endif
1.162     brouard  2334:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2335: #ifdef DEBUG
1.224     brouard  2336:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2337:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2338: #endif
1.126     brouard  2339:       fu=(*func)(u); 
                   2340:       if (fu < *fc) { 
1.183     brouard  2341: #ifdef DEBUG
1.224     brouard  2342:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2343:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2344: #endif
                   2345:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2346:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2347: #ifdef DEBUG
                   2348:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2349: #endif
                   2350:       } 
1.162     brouard  2351:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2352: #ifdef DEBUG
1.224     brouard  2353:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2354:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2355: #endif
1.126     brouard  2356:       u=ulim; 
                   2357:       fu=(*func)(u); 
1.183     brouard  2358:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2359: #ifdef DEBUG
1.224     brouard  2360:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2361:       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  2362: #endif
1.126     brouard  2363:       u=(*cx)+GOLD*(*cx-*bx); 
                   2364:       fu=(*func)(u); 
1.224     brouard  2365: #ifdef DEBUG
                   2366:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2367:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2368: #endif
1.183     brouard  2369:     } /* end tests */
1.126     brouard  2370:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2371:     SHFT(*fa,*fb,*fc,fu) 
                   2372: #ifdef DEBUG
1.224     brouard  2373:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2374:       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  2375: #endif
                   2376:   } /* 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  2377: } 
                   2378: 
                   2379: /*************** linmin ************************/
1.162     brouard  2380: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2381: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2382: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2383: the value of func at the returned location p . This is actually all accomplished by calling the
                   2384: routines mnbrak and brent .*/
1.126     brouard  2385: int ncom; 
                   2386: double *pcom,*xicom;
                   2387: double (*nrfunc)(double []); 
                   2388:  
1.224     brouard  2389: #ifdef LINMINORIGINAL
1.126     brouard  2390: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2391: #else
                   2392: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2393: #endif
1.126     brouard  2394: { 
                   2395:   double brent(double ax, double bx, double cx, 
                   2396:               double (*f)(double), double tol, double *xmin); 
                   2397:   double f1dim(double x); 
                   2398:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2399:              double *fc, double (*func)(double)); 
                   2400:   int j; 
                   2401:   double xx,xmin,bx,ax; 
                   2402:   double fx,fb,fa;
1.187     brouard  2403: 
1.203     brouard  2404: #ifdef LINMINORIGINAL
                   2405: #else
                   2406:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2407: #endif
                   2408:   
1.126     brouard  2409:   ncom=n; 
                   2410:   pcom=vector(1,n); 
                   2411:   xicom=vector(1,n); 
                   2412:   nrfunc=func; 
                   2413:   for (j=1;j<=n;j++) { 
                   2414:     pcom[j]=p[j]; 
1.202     brouard  2415:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2416:   } 
1.187     brouard  2417: 
1.203     brouard  2418: #ifdef LINMINORIGINAL
                   2419:   xx=1.;
                   2420: #else
                   2421:   axs=0.0;
                   2422:   xxs=1.;
                   2423:   do{
                   2424:     xx= xxs;
                   2425: #endif
1.187     brouard  2426:     ax=0.;
                   2427:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2428:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2429:     /* 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))   */
                   2430:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2431:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2432:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2433:     /* 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  2434: #ifdef LINMINORIGINAL
                   2435: #else
                   2436:     if (fx != fx){
1.224     brouard  2437:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2438:                        printf("|");
                   2439:                        fprintf(ficlog,"|");
1.203     brouard  2440: #ifdef DEBUGLINMIN
1.224     brouard  2441:                        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  2442: #endif
                   2443:     }
1.224     brouard  2444:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2445: #endif
                   2446:   
1.191     brouard  2447: #ifdef DEBUGLINMIN
                   2448:   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  2449:   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  2450: #endif
1.224     brouard  2451: #ifdef LINMINORIGINAL
                   2452: #else
1.317     brouard  2453:   if(fb == fx){ /* Flat function in the direction */
                   2454:     xmin=xx;
1.224     brouard  2455:     *flat=1;
1.317     brouard  2456:   }else{
1.224     brouard  2457:     *flat=0;
                   2458: #endif
                   2459:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2460:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2461:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2462:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2463:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2464:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2465: #ifdef DEBUG
1.224     brouard  2466:   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);
                   2467:   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);
                   2468: #endif
                   2469: #ifdef LINMINORIGINAL
                   2470: #else
                   2471:                        }
1.126     brouard  2472: #endif
1.191     brouard  2473: #ifdef DEBUGLINMIN
                   2474:   printf("linmin end ");
1.202     brouard  2475:   fprintf(ficlog,"linmin end ");
1.191     brouard  2476: #endif
1.126     brouard  2477:   for (j=1;j<=n;j++) { 
1.203     brouard  2478: #ifdef LINMINORIGINAL
                   2479:     xi[j] *= xmin; 
                   2480: #else
                   2481: #ifdef DEBUGLINMIN
                   2482:     if(xxs <1.0)
                   2483:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2484: #endif
                   2485:     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) */
                   2486: #ifdef DEBUGLINMIN
                   2487:     if(xxs <1.0)
                   2488:       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 );
                   2489: #endif
                   2490: #endif
1.187     brouard  2491:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2492:   } 
1.191     brouard  2493: #ifdef DEBUGLINMIN
1.203     brouard  2494:   printf("\n");
1.191     brouard  2495:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2496:   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  2497:   for (j=1;j<=n;j++) { 
1.202     brouard  2498:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2499:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2500:     if(j % ncovmodel == 0){
1.191     brouard  2501:       printf("\n");
1.202     brouard  2502:       fprintf(ficlog,"\n");
                   2503:     }
1.191     brouard  2504:   }
1.203     brouard  2505: #else
1.191     brouard  2506: #endif
1.126     brouard  2507:   free_vector(xicom,1,n); 
                   2508:   free_vector(pcom,1,n); 
                   2509: } 
                   2510: 
                   2511: 
                   2512: /*************** powell ************************/
1.162     brouard  2513: /*
1.317     brouard  2514: Minimization of a function func of n variables. Input consists in an initial starting point
                   2515: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2516: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2517: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2518: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2519: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2520:  */
1.224     brouard  2521: #ifdef LINMINORIGINAL
                   2522: #else
                   2523:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2524:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2525: #endif
1.126     brouard  2526: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2527:            double (*func)(double [])) 
                   2528: { 
1.224     brouard  2529: #ifdef LINMINORIGINAL
                   2530:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2531:              double (*func)(double [])); 
1.224     brouard  2532: #else 
1.241     brouard  2533:  void linmin(double p[], double xi[], int n, double *fret,
                   2534:             double (*func)(double []),int *flat); 
1.224     brouard  2535: #endif
1.239     brouard  2536:  int i,ibig,j,jk,k; 
1.126     brouard  2537:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2538:   double directest;
1.126     brouard  2539:   double fp,fptt;
                   2540:   double *xits;
                   2541:   int niterf, itmp;
                   2542: 
                   2543:   pt=vector(1,n); 
                   2544:   ptt=vector(1,n); 
                   2545:   xit=vector(1,n); 
                   2546:   xits=vector(1,n); 
                   2547:   *fret=(*func)(p); 
                   2548:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2549:   rcurr_time = time(NULL);
                   2550:   fp=(*fret); /* Initialisation */
1.126     brouard  2551:   for (*iter=1;;++(*iter)) { 
                   2552:     ibig=0; 
                   2553:     del=0.0; 
1.157     brouard  2554:     rlast_time=rcurr_time;
                   2555:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2556:     rcurr_time = time(NULL);  
                   2557:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2558:     /* 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); */
                   2559:     /* 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); */
                   2560:     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);
                   2561:     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  2562: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2563:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2564:     for (i=1;i<=n;i++) {
1.126     brouard  2565:       fprintf(ficrespow," %.12lf", p[i]);
                   2566:     }
1.239     brouard  2567:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2568:     printf("\n#model=  1      +     age ");
                   2569:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2570:     if(nagesqr==1){
1.241     brouard  2571:        printf("  + age*age  ");
                   2572:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2573:     }
                   2574:     for(j=1;j <=ncovmodel-2;j++){
                   2575:       if(Typevar[j]==0) {
                   2576:        printf("  +      V%d  ",Tvar[j]);
                   2577:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2578:       }else if(Typevar[j]==1) {
                   2579:        printf("  +    V%d*age ",Tvar[j]);
                   2580:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2581:       }else if(Typevar[j]==2) {
                   2582:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2583:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2584:       }
                   2585:     }
1.126     brouard  2586:     printf("\n");
1.239     brouard  2587: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2588: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2589:     fprintf(ficlog,"\n");
1.239     brouard  2590:     for(i=1,jk=1; i <=nlstate; i++){
                   2591:       for(k=1; k <=(nlstate+ndeath); k++){
                   2592:        if (k != i) {
                   2593:          printf("%d%d ",i,k);
                   2594:          fprintf(ficlog,"%d%d ",i,k);
                   2595:          for(j=1; j <=ncovmodel; j++){
                   2596:            printf("%12.7f ",p[jk]);
                   2597:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2598:            jk++; 
                   2599:          }
                   2600:          printf("\n");
                   2601:          fprintf(ficlog,"\n");
                   2602:        }
                   2603:       }
                   2604:     }
1.241     brouard  2605:     if(*iter <=3 && *iter >1){
1.157     brouard  2606:       tml = *localtime(&rcurr_time);
                   2607:       strcpy(strcurr,asctime(&tml));
                   2608:       rforecast_time=rcurr_time; 
1.126     brouard  2609:       itmp = strlen(strcurr);
                   2610:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2611:        strcurr[itmp-1]='\0';
1.162     brouard  2612:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2613:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2614:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2615:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2616:        forecast_time = *localtime(&rforecast_time);
                   2617:        strcpy(strfor,asctime(&forecast_time));
                   2618:        itmp = strlen(strfor);
                   2619:        if(strfor[itmp-1]=='\n')
                   2620:          strfor[itmp-1]='\0';
                   2621:        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);
                   2622:        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  2623:       }
                   2624:     }
1.187     brouard  2625:     for (i=1;i<=n;i++) { /* For each direction i */
                   2626:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2627:       fptt=(*fret); 
                   2628: #ifdef DEBUG
1.203     brouard  2629:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2630:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2631: #endif
1.203     brouard  2632:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2633:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2634: #ifdef LINMINORIGINAL
1.188     brouard  2635:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2636: #else
                   2637:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2638:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2639: #endif
                   2640:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2641:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2642:                                /* because that direction will be replaced unless the gain del is small */
                   2643:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2644:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2645:                                /* with the new direction. */
                   2646:                                del=fabs(fptt-(*fret)); 
                   2647:                                ibig=i; 
1.126     brouard  2648:       } 
                   2649: #ifdef DEBUG
                   2650:       printf("%d %.12e",i,(*fret));
                   2651:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2652:       for (j=1;j<=n;j++) {
1.224     brouard  2653:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2654:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2655:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2656:       }
                   2657:       for(j=1;j<=n;j++) {
1.225     brouard  2658:                                printf(" p(%d)=%.12e",j,p[j]);
                   2659:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2660:       }
                   2661:       printf("\n");
                   2662:       fprintf(ficlog,"\n");
                   2663: #endif
1.187     brouard  2664:     } /* end loop on each direction i */
                   2665:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2666:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2667:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2668:     for(j=1;j<=n;j++) {
                   2669:       if(flatdir[j] >0){
                   2670:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2671:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2672:       }
1.319     brouard  2673:       /* printf("\n"); */
                   2674:       /* fprintf(ficlog,"\n"); */
                   2675:     }
1.243     brouard  2676:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2677:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2678:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2679:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2680:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2681:       /* decreased of more than 3.84  */
                   2682:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2683:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2684:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2685:                        
1.188     brouard  2686:       /* Starting the program with initial values given by a former maximization will simply change */
                   2687:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2688:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2689:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2690: #ifdef DEBUG
                   2691:       int k[2],l;
                   2692:       k[0]=1;
                   2693:       k[1]=-1;
                   2694:       printf("Max: %.12e",(*func)(p));
                   2695:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2696:       for (j=1;j<=n;j++) {
                   2697:        printf(" %.12e",p[j]);
                   2698:        fprintf(ficlog," %.12e",p[j]);
                   2699:       }
                   2700:       printf("\n");
                   2701:       fprintf(ficlog,"\n");
                   2702:       for(l=0;l<=1;l++) {
                   2703:        for (j=1;j<=n;j++) {
                   2704:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2705:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2706:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2707:        }
                   2708:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2709:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2710:       }
                   2711: #endif
                   2712: 
                   2713:       free_vector(xit,1,n); 
                   2714:       free_vector(xits,1,n); 
                   2715:       free_vector(ptt,1,n); 
                   2716:       free_vector(pt,1,n); 
                   2717:       return; 
1.192     brouard  2718:     } /* enough precision */ 
1.240     brouard  2719:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2720:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2721:       ptt[j]=2.0*p[j]-pt[j]; 
                   2722:       xit[j]=p[j]-pt[j]; 
                   2723:       pt[j]=p[j]; 
                   2724:     } 
1.181     brouard  2725:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2726: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2727:                if (*iter <=4) {
1.225     brouard  2728: #else
                   2729: #endif
1.224     brouard  2730: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2731: #else
1.161     brouard  2732:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2733: #endif
1.162     brouard  2734:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2735:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2736:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2737:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2738:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2739:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2740:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2741:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2742:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2743:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2744:       /* mu² and del² are equal when f3=f1 */
                   2745:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2746:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2747:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2748:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2749: #ifdef NRCORIGINAL
                   2750:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2751: #else
                   2752:       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  2753:       t= t- del*SQR(fp-fptt);
1.183     brouard  2754: #endif
1.202     brouard  2755:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2756: #ifdef DEBUG
1.181     brouard  2757:       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);
                   2758:       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  2759:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2760:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2761:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2762:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2763:       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);
                   2764:       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);
                   2765: #endif
1.183     brouard  2766: #ifdef POWELLORIGINAL
                   2767:       if (t < 0.0) { /* Then we use it for new direction */
                   2768: #else
1.182     brouard  2769:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2770:                                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  2771:         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  2772:         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  2773:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2774:       } 
1.181     brouard  2775:       if (directest < 0.0) { /* Then we use it for new direction */
                   2776: #endif
1.191     brouard  2777: #ifdef DEBUGLINMIN
1.234     brouard  2778:        printf("Before linmin in direction P%d-P0\n",n);
                   2779:        for (j=1;j<=n;j++) {
                   2780:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2781:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2782:          if(j % ncovmodel == 0){
                   2783:            printf("\n");
                   2784:            fprintf(ficlog,"\n");
                   2785:          }
                   2786:        }
1.224     brouard  2787: #endif
                   2788: #ifdef LINMINORIGINAL
1.234     brouard  2789:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2790: #else
1.234     brouard  2791:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2792:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2793: #endif
1.234     brouard  2794:        
1.191     brouard  2795: #ifdef DEBUGLINMIN
1.234     brouard  2796:        for (j=1;j<=n;j++) { 
                   2797:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2798:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2799:          if(j % ncovmodel == 0){
                   2800:            printf("\n");
                   2801:            fprintf(ficlog,"\n");
                   2802:          }
                   2803:        }
1.224     brouard  2804: #endif
1.234     brouard  2805:        for (j=1;j<=n;j++) { 
                   2806:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2807:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2808:        }
1.224     brouard  2809: #ifdef LINMINORIGINAL
                   2810: #else
1.234     brouard  2811:        for (j=1, flatd=0;j<=n;j++) {
                   2812:          if(flatdir[j]>0)
                   2813:            flatd++;
                   2814:        }
                   2815:        if(flatd >0){
1.255     brouard  2816:          printf("%d flat directions: ",flatd);
                   2817:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2818:          for (j=1;j<=n;j++) { 
                   2819:            if(flatdir[j]>0){
                   2820:              printf("%d ",j);
                   2821:              fprintf(ficlog,"%d ",j);
                   2822:            }
                   2823:          }
                   2824:          printf("\n");
                   2825:          fprintf(ficlog,"\n");
1.319     brouard  2826: #ifdef FLATSUP
                   2827:           free_vector(xit,1,n); 
                   2828:           free_vector(xits,1,n); 
                   2829:           free_vector(ptt,1,n); 
                   2830:           free_vector(pt,1,n); 
                   2831:           return;
                   2832: #endif
1.234     brouard  2833:        }
1.191     brouard  2834: #endif
1.234     brouard  2835:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2836:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2837:        
1.126     brouard  2838: #ifdef DEBUG
1.234     brouard  2839:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2840:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2841:        for(j=1;j<=n;j++){
                   2842:          printf(" %lf",xit[j]);
                   2843:          fprintf(ficlog," %lf",xit[j]);
                   2844:        }
                   2845:        printf("\n");
                   2846:        fprintf(ficlog,"\n");
1.126     brouard  2847: #endif
1.192     brouard  2848:       } /* end of t or directest negative */
1.224     brouard  2849: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2850: #else
1.234     brouard  2851:       } /* end if (fptt < fp)  */
1.192     brouard  2852: #endif
1.225     brouard  2853: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2854:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2855: #else
1.224     brouard  2856: #endif
1.234     brouard  2857:                } /* loop iteration */ 
1.126     brouard  2858: } 
1.234     brouard  2859:   
1.126     brouard  2860: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2861:   
1.235     brouard  2862:   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  2863:   {
1.338     brouard  2864:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2865:      *   (and selected quantitative values in nres)
                   2866:      *  by left multiplying the unit
                   2867:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2868:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2869:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2870:      * or prevalence in state 1, prevalence in state 2, 0
                   2871:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2872:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2873:      * Output is prlim.
                   2874:      * Initial matrix pimij 
                   2875:      */
1.206     brouard  2876:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2877:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2878:   /*  0,                   0                  , 1} */
                   2879:   /*
                   2880:    * and after some iteration: */
                   2881:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2882:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2883:   /*  0,                   0                  , 1} */
                   2884:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2885:   /* {0.51571254859325999, 0.4842874514067399, */
                   2886:   /*  0.51326036147820708, 0.48673963852179264} */
                   2887:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2888:     
1.332     brouard  2889:     int i, ii,j,k, k1;
1.209     brouard  2890:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2891:   /* double **matprod2(); */ /* test */
1.218     brouard  2892:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2893:   double **newm;
1.209     brouard  2894:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2895:   int ncvloop=0;
1.288     brouard  2896:   int first=0;
1.169     brouard  2897:   
1.209     brouard  2898:   min=vector(1,nlstate);
                   2899:   max=vector(1,nlstate);
                   2900:   meandiff=vector(1,nlstate);
                   2901: 
1.218     brouard  2902:        /* Starting with matrix unity */
1.126     brouard  2903:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2904:     for (j=1;j<=nlstate+ndeath;j++){
                   2905:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2906:     }
1.169     brouard  2907:   
                   2908:   cov[1]=1.;
                   2909:   
                   2910:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2911:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2912:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2913:     ncvloop++;
1.126     brouard  2914:     newm=savm;
                   2915:     /* Covariates have to be included here again */
1.138     brouard  2916:     cov[2]=agefin;
1.319     brouard  2917:      if(nagesqr==1){
                   2918:       cov[3]= agefin*agefin;
                   2919:      }
1.332     brouard  2920:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2921:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2922:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2923:        if(Typevar[k1]==1){ /* A product with age */
                   2924:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2925:        }else{
                   2926:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2927:        }
                   2928:      }/* End of loop on model equation */
                   2929:      
                   2930: /* Start of old code (replaced by a loop on position in the model equation */
                   2931:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2932:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2933:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2934:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2935:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2936:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2937:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2938:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2939:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2940:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2941:     /*    *nsd=3                              (1)  (2)           (3) */
                   2942:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2943:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2944:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2945:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2946:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2947:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2948:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2949:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2950:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2951:     /*    *TvarsDpType */
                   2952:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2953:     /*    * nsd=1              (1)           (2) */
                   2954:     /*    *TvarsD[nsd]          3             2 */
                   2955:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2956:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2957:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2958:     /*    *\/ */
                   2959:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2960:     /*   /\* 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)); *\/ */
                   2961:     /* } */
                   2962:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2963:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2964:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2965:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2966:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2967:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2968:     /*   /\* 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]); *\/ */
                   2969:     /* } */
                   2970:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2971:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2972:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2973:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2974:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2975:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2976:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2977:     /*   } */
                   2978:     /*   /\* 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]); *\/ */
                   2979:     /* } */
                   2980:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2981:     /*   /\* 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]); *\/ */
                   2982:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2983:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2984:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2985:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2986:     /*         }else{ */
                   2987:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2988:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2989:     /*         } */
                   2990:     /*   }else{ */
                   2991:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2992:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2993:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2994:     /*         }else{ */
                   2995:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2996:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2997:     /*         } */
                   2998:     /*   } */
                   2999:     /* } /\* End product without age *\/ */
                   3000: /* ENd of old code */
1.138     brouard  3001:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3002:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3003:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3004:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3005:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3006:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3007:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3008:     
1.126     brouard  3009:     savm=oldm;
                   3010:     oldm=newm;
1.209     brouard  3011: 
                   3012:     for(j=1; j<=nlstate; j++){
                   3013:       max[j]=0.;
                   3014:       min[j]=1.;
                   3015:     }
                   3016:     for(i=1;i<=nlstate;i++){
                   3017:       sumnew=0;
                   3018:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3019:       for(j=1; j<=nlstate; j++){ 
                   3020:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3021:        max[j]=FMAX(max[j],prlim[i][j]);
                   3022:        min[j]=FMIN(min[j],prlim[i][j]);
                   3023:       }
                   3024:     }
                   3025: 
1.126     brouard  3026:     maxmax=0.;
1.209     brouard  3027:     for(j=1; j<=nlstate; j++){
                   3028:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3029:       maxmax=FMAX(maxmax,meandiff[j]);
                   3030:       /* 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  3031:     } /* j loop */
1.203     brouard  3032:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3033:     /* 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  3034:     if(maxmax < ftolpl){
1.209     brouard  3035:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3036:       free_vector(min,1,nlstate);
                   3037:       free_vector(max,1,nlstate);
                   3038:       free_vector(meandiff,1,nlstate);
1.126     brouard  3039:       return prlim;
                   3040:     }
1.288     brouard  3041:   } /* agefin loop */
1.208     brouard  3042:     /* After some age loop it doesn't converge */
1.288     brouard  3043:   if(!first){
                   3044:     first=1;
                   3045:     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  3046:     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);
                   3047:   }else if (first >=1 && first <10){
                   3048:     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);
                   3049:     first++;
                   3050:   }else if (first ==10){
                   3051:     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);
                   3052:     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");
                   3053:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3054:     first++;
1.288     brouard  3055:   }
                   3056: 
1.209     brouard  3057:   /* 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); */
                   3058:   free_vector(min,1,nlstate);
                   3059:   free_vector(max,1,nlstate);
                   3060:   free_vector(meandiff,1,nlstate);
1.208     brouard  3061:   
1.169     brouard  3062:   return prlim; /* should not reach here */
1.126     brouard  3063: }
                   3064: 
1.217     brouard  3065: 
                   3066:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3067: 
1.218     brouard  3068:  /* 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) */
                   3069:  /* 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  3070:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3071: {
1.264     brouard  3072:   /* 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  3073:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3074:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3075:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3076:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3077:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3078:   /* Initial matrix pimij */
                   3079:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3080:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3081:   /*  0,                   0                  , 1} */
                   3082:   /*
                   3083:    * and after some iteration: */
                   3084:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3085:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3086:   /*  0,                   0                  , 1} */
                   3087:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3088:   /* {0.51571254859325999, 0.4842874514067399, */
                   3089:   /*  0.51326036147820708, 0.48673963852179264} */
                   3090:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3091: 
1.332     brouard  3092:   int i, ii,j,k, k1;
1.247     brouard  3093:   int first=0;
1.217     brouard  3094:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3095:   /* double **matprod2(); */ /* test */
                   3096:   double **out, cov[NCOVMAX+1], **bmij();
                   3097:   double **newm;
1.218     brouard  3098:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3099:   double        **oldm, **savm;  /* for use */
                   3100: 
1.217     brouard  3101:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3102:   int ncvloop=0;
                   3103:   
                   3104:   min=vector(1,nlstate);
                   3105:   max=vector(1,nlstate);
                   3106:   meandiff=vector(1,nlstate);
                   3107: 
1.266     brouard  3108:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3109:   oldm=oldms; savm=savms;
                   3110:   
                   3111:   /* Starting with matrix unity */
                   3112:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3113:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3114:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3115:     }
                   3116:   
                   3117:   cov[1]=1.;
                   3118:   
                   3119:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3120:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3121:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3122:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3123:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3124:     ncvloop++;
1.218     brouard  3125:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3126:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3127:     /* Covariates have to be included here again */
                   3128:     cov[2]=agefin;
1.319     brouard  3129:     if(nagesqr==1){
1.217     brouard  3130:       cov[3]= agefin*agefin;;
1.319     brouard  3131:     }
1.332     brouard  3132:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3133:       if(Typevar[k1]==1){ /* A product with age */
                   3134:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3135:       }else{
1.332     brouard  3136:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3137:       }
1.332     brouard  3138:     }/* End of loop on model equation */
                   3139: 
                   3140: /* Old code */ 
                   3141: 
                   3142:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3143:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3144:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3145:     /*   /\* 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)); *\/ */
                   3146:     /* } */
                   3147:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3148:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3149:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3150:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3151:     /* /\* } *\/ */
                   3152:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3153:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3154:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3155:     /*   /\* 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]); *\/ */
                   3156:     /* } */
                   3157:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3158:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3159:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3160:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3161:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3162:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3163:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3164:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3165:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3166:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3167:     /*   } */
                   3168:     /*   /\* 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]); *\/ */
                   3169:     /* } */
                   3170:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3171:     /*   /\* 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]); *\/ */
                   3172:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3173:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3174:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3175:     /*         }else{ */
                   3176:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3177:     /*         } */
                   3178:     /*   }else{ */
                   3179:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3180:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3181:     /*         }else{ */
                   3182:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3183:     /*         } */
                   3184:     /*   } */
                   3185:     /* } */
1.217     brouard  3186:     
                   3187:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3188:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3189:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3190:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3191:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3192:                /* ij should be linked to the correct index of cov */
                   3193:                /* age and covariate values ij are in 'cov', but we need to pass
                   3194:                 * ij for the observed prevalence at age and status and covariate
                   3195:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3196:                 */
                   3197:     /* 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 *\/ */
                   3198:     /* 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 *\/ */
                   3199:     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  3200:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3201:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3202:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3203:     /*         printf("%d newm= ",i); */
                   3204:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3205:     /*           printf("%f ",newm[i][j]); */
                   3206:     /*         } */
                   3207:     /*         printf("oldm * "); */
                   3208:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3209:     /*           printf("%f ",oldm[i][j]); */
                   3210:     /*         } */
1.268     brouard  3211:     /*         printf(" bmmij "); */
1.266     brouard  3212:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3213:     /*           printf("%f ",pmmij[i][j]); */
                   3214:     /*         } */
                   3215:     /*         printf("\n"); */
                   3216:     /*   } */
                   3217:     /* } */
1.217     brouard  3218:     savm=oldm;
                   3219:     oldm=newm;
1.266     brouard  3220: 
1.217     brouard  3221:     for(j=1; j<=nlstate; j++){
                   3222:       max[j]=0.;
                   3223:       min[j]=1.;
                   3224:     }
                   3225:     for(j=1; j<=nlstate; j++){ 
                   3226:       for(i=1;i<=nlstate;i++){
1.234     brouard  3227:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3228:        bprlim[i][j]= newm[i][j];
                   3229:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3230:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3231:       }
                   3232:     }
1.218     brouard  3233:                
1.217     brouard  3234:     maxmax=0.;
                   3235:     for(i=1; i<=nlstate; i++){
1.318     brouard  3236:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3237:       maxmax=FMAX(maxmax,meandiff[i]);
                   3238:       /* 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  3239:     } /* i loop */
1.217     brouard  3240:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3241:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3242:     if(maxmax < ftolpl){
1.220     brouard  3243:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3244:       free_vector(min,1,nlstate);
                   3245:       free_vector(max,1,nlstate);
                   3246:       free_vector(meandiff,1,nlstate);
                   3247:       return bprlim;
                   3248:     }
1.288     brouard  3249:   } /* agefin loop */
1.217     brouard  3250:     /* After some age loop it doesn't converge */
1.288     brouard  3251:   if(!first){
1.247     brouard  3252:     first=1;
                   3253:     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\
                   3254: 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);
                   3255:   }
                   3256:   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  3257: 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);
                   3258:   /* 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); */
                   3259:   free_vector(min,1,nlstate);
                   3260:   free_vector(max,1,nlstate);
                   3261:   free_vector(meandiff,1,nlstate);
                   3262:   
                   3263:   return bprlim; /* should not reach here */
                   3264: }
                   3265: 
1.126     brouard  3266: /*************** transition probabilities ***************/ 
                   3267: 
                   3268: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3269: {
1.138     brouard  3270:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3271:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3272:      model to the ncovmodel covariates (including constant and age).
                   3273:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3274:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3275:      ncth covariate in the global vector x is given by the formula:
                   3276:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3277:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3278:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3279:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3280:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3281:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3282:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3283:   */
                   3284:   double s1, lnpijopii;
1.126     brouard  3285:   /*double t34;*/
1.164     brouard  3286:   int i,j, nc, ii, jj;
1.126     brouard  3287: 
1.223     brouard  3288:   for(i=1; i<= nlstate; i++){
                   3289:     for(j=1; j<i;j++){
                   3290:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3291:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3292:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3293:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3294:       }
                   3295:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3296:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3297:     }
                   3298:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3299:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3300:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3301:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3302:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3303:       }
                   3304:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3305:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3306:     }
                   3307:   }
1.218     brouard  3308:   
1.223     brouard  3309:   for(i=1; i<= nlstate; i++){
                   3310:     s1=0;
                   3311:     for(j=1; j<i; j++){
1.339     brouard  3312:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3313:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3314:     }
                   3315:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3316:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3317:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3318:     }
                   3319:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3320:     ps[i][i]=1./(s1+1.);
                   3321:     /* Computing other pijs */
                   3322:     for(j=1; j<i; j++)
1.325     brouard  3323:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3324:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3325:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3326:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3327:   } /* end i */
1.218     brouard  3328:   
1.223     brouard  3329:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3330:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3331:       ps[ii][jj]=0;
                   3332:       ps[ii][ii]=1;
                   3333:     }
                   3334:   }
1.294     brouard  3335: 
                   3336: 
1.223     brouard  3337:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3338:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3339:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3340:   /*   } */
                   3341:   /*   printf("\n "); */
                   3342:   /* } */
                   3343:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3344:   /*
                   3345:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3346:                goto end;*/
1.266     brouard  3347:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3348: }
                   3349: 
1.218     brouard  3350: /*************** backward transition probabilities ***************/ 
                   3351: 
                   3352:  /* 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 ) */
                   3353: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3354:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3355: {
1.302     brouard  3356:   /* 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  3357:    * 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  3358:    */
1.218     brouard  3359:   int i, ii, j,k;
1.222     brouard  3360:   
                   3361:   double **out, **pmij();
                   3362:   double sumnew=0.;
1.218     brouard  3363:   double agefin;
1.292     brouard  3364:   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  3365:   double **dnewm, **dsavm, **doldm;
                   3366:   double **bbmij;
                   3367:   
1.218     brouard  3368:   doldm=ddoldms; /* global pointers */
1.222     brouard  3369:   dnewm=ddnewms;
                   3370:   dsavm=ddsavms;
1.318     brouard  3371: 
                   3372:   /* Debug */
                   3373:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3374:   agefin=cov[2];
1.268     brouard  3375:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3376:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3377:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3378:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3379: 
                   3380:   /* P_x */
1.325     brouard  3381:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3382:   /* outputs pmmij which is a stochastic matrix in row */
                   3383: 
                   3384:   /* Diag(w_x) */
1.292     brouard  3385:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3386:   sumnew=0.;
1.269     brouard  3387:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3388:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3389:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3390:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3391:   }
                   3392:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3393:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3394:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3395:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3396:     }
                   3397:   }else{
                   3398:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3399:       for (j=1;j<=nlstate+ndeath;j++)
                   3400:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3401:     }
                   3402:     /* if(sumnew <0.9){ */
                   3403:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3404:     /* } */
                   3405:   }
                   3406:   k3=0.0;  /* We put the last diagonal to 0 */
                   3407:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3408:       doldm[ii][ii]= k3;
                   3409:   }
                   3410:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3411:   
1.292     brouard  3412:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3413:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3414: 
1.292     brouard  3415:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3416:   /* 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  3417:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3418:     sumnew=0.;
1.222     brouard  3419:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3420:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3421:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3422:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3423:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3424:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3425:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3426:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3427:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3428:        /* }else */
1.268     brouard  3429:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3430:     } /*End ii */
                   3431:   } /* 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 */
                   3432: 
1.292     brouard  3433:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3434:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3435:   /* end bmij */
1.266     brouard  3436:   return ps; /*pointer is unchanged */
1.218     brouard  3437: }
1.217     brouard  3438: /*************** transition probabilities ***************/ 
                   3439: 
1.218     brouard  3440: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3441: {
                   3442:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3443:      computes the probability to be observed in state j being in state i by appying the
                   3444:      model to the ncovmodel covariates (including constant and age).
                   3445:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3446:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3447:      ncth covariate in the global vector x is given by the formula:
                   3448:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3449:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3450:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3451:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3452:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3453:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3454:   */
                   3455:   double s1, lnpijopii;
                   3456:   /*double t34;*/
                   3457:   int i,j, nc, ii, jj;
                   3458: 
1.234     brouard  3459:   for(i=1; i<= nlstate; i++){
                   3460:     for(j=1; j<i;j++){
                   3461:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3462:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3463:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3464:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3465:       }
                   3466:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3467:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3468:     }
                   3469:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3470:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3471:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3472:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3473:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3474:       }
                   3475:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3476:     }
                   3477:   }
                   3478:   
                   3479:   for(i=1; i<= nlstate; i++){
                   3480:     s1=0;
                   3481:     for(j=1; j<i; j++){
                   3482:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3483:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3484:     }
                   3485:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3486:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3487:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3488:     }
                   3489:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3490:     ps[i][i]=1./(s1+1.);
                   3491:     /* Computing other pijs */
                   3492:     for(j=1; j<i; j++)
                   3493:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3494:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3495:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3496:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3497:   } /* end i */
                   3498:   
                   3499:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3500:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3501:       ps[ii][jj]=0;
                   3502:       ps[ii][ii]=1;
                   3503:     }
                   3504:   }
1.296     brouard  3505:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3506:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3507:     s1=0.;
                   3508:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3509:       s1+=ps[ii][jj];
                   3510:     }
                   3511:     for(ii=1; ii<= nlstate; ii++){
                   3512:       ps[ii][jj]=ps[ii][jj]/s1;
                   3513:     }
                   3514:   }
                   3515:   /* Transposition */
                   3516:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3517:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3518:       s1=ps[ii][jj];
                   3519:       ps[ii][jj]=ps[jj][ii];
                   3520:       ps[jj][ii]=s1;
                   3521:     }
                   3522:   }
                   3523:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3524:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3525:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3526:   /*   } */
                   3527:   /*   printf("\n "); */
                   3528:   /* } */
                   3529:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3530:   /*
                   3531:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3532:     goto end;*/
                   3533:   return ps;
1.217     brouard  3534: }
                   3535: 
                   3536: 
1.126     brouard  3537: /**************** Product of 2 matrices ******************/
                   3538: 
1.145     brouard  3539: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3540: {
                   3541:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3542:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3543:   /* in, b, out are matrice of pointers which should have been initialized 
                   3544:      before: only the contents of out is modified. The function returns
                   3545:      a pointer to pointers identical to out */
1.145     brouard  3546:   int i, j, k;
1.126     brouard  3547:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3548:     for(k=ncolol; k<=ncoloh; k++){
                   3549:       out[i][k]=0.;
                   3550:       for(j=ncl; j<=nch; j++)
                   3551:        out[i][k] +=in[i][j]*b[j][k];
                   3552:     }
1.126     brouard  3553:   return out;
                   3554: }
                   3555: 
                   3556: 
                   3557: /************* Higher Matrix Product ***************/
                   3558: 
1.235     brouard  3559: 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  3560: {
1.336     brouard  3561:   /* Already optimized with precov.
                   3562:      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  3563:      'nhstepm*hstepm*stepm' months (i.e. until
                   3564:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3565:      nhstepm*hstepm matrices. 
                   3566:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3567:      (typically every 2 years instead of every month which is too big 
                   3568:      for the memory).
                   3569:      Model is determined by parameters x and covariates have to be 
                   3570:      included manually here. 
                   3571: 
                   3572:      */
                   3573: 
1.330     brouard  3574:   int i, j, d, h, k, k1;
1.131     brouard  3575:   double **out, cov[NCOVMAX+1];
1.126     brouard  3576:   double **newm;
1.187     brouard  3577:   double agexact;
1.214     brouard  3578:   double agebegin, ageend;
1.126     brouard  3579: 
                   3580:   /* Hstepm could be zero and should return the unit matrix */
                   3581:   for (i=1;i<=nlstate+ndeath;i++)
                   3582:     for (j=1;j<=nlstate+ndeath;j++){
                   3583:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3584:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3585:     }
                   3586:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3587:   for(h=1; h <=nhstepm; h++){
                   3588:     for(d=1; d <=hstepm; d++){
                   3589:       newm=savm;
                   3590:       /* Covariates have to be included here again */
                   3591:       cov[1]=1.;
1.214     brouard  3592:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3593:       cov[2]=agexact;
1.319     brouard  3594:       if(nagesqr==1){
1.227     brouard  3595:        cov[3]= agexact*agexact;
1.319     brouard  3596:       }
1.330     brouard  3597:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3598:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3599:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3600:        if(Typevar[k1]==1){ /* A product with age */
                   3601:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3602:        }else{
                   3603:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3604:        }
                   3605:       }/* End of loop on model equation */
                   3606:        /* Old code */ 
                   3607: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3608: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3609: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3610: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3611: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3612: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3613: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3614: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3615: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3616: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3617: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3618: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3619: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3620: /*       /\* 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]])); *\/ */
                   3621: /*       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); */
                   3622: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3623: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3624: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3625: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3626: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3627: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3628: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3629: /*       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]]); */
                   3630: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3631: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3632: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3633: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3634: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3635: /*       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]); */
                   3636: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3637: 
                   3638: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3639: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3640: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3641: /*       /\* *\/ */
1.330     brouard  3642: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3643: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3644: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3645: /* /\*cptcovage=2                   1               2      *\/ */
                   3646: /* /\*Tage[k]=                      5               8      *\/  */
                   3647: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3648: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3649: /*       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]]); */
                   3650: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3651: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3652: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3653: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3654: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3655: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3656: /*       /\*   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); *\/ */
                   3657: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3658: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3659: /*       /\* } *\/ */
                   3660: /*       /\* 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]); *\/ */
                   3661: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3662: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3663: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3664: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3665: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3666: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3667: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3668: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3669: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3670:          
1.332     brouard  3671: /*       /\* 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])]); *\/ */
                   3672: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3673: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3674: /*       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]]); */
                   3675: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3676: 
                   3677: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3678: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3679: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3680: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3681: /*           /\* 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]])]; *\/ */
                   3682: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3683: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3684: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3685: /*       /\*   } *\/ */
                   3686: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3687: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3688: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3689: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3690: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3691: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3692: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3693: /*       /\*   } *\/ */
                   3694: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3695: /*     }/\*end of products *\/ */
                   3696:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3697:       /* for (k=1; k<=cptcovn;k++)  */
                   3698:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3699:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3700:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3701:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3702:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3703:       
                   3704:       
1.126     brouard  3705:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3706:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3707:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3708:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3709:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3710:       /* if((int)age == 70){ */
                   3711:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3712:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3713:       /*         printf("%d pmmij ",i); */
                   3714:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3715:       /*           printf("%f ",pmmij[i][j]); */
                   3716:       /*         } */
                   3717:       /*         printf(" oldm "); */
                   3718:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3719:       /*           printf("%f ",oldm[i][j]); */
                   3720:       /*         } */
                   3721:       /*         printf("\n"); */
                   3722:       /*       } */
                   3723:       /* } */
1.126     brouard  3724:       savm=oldm;
                   3725:       oldm=newm;
                   3726:     }
                   3727:     for(i=1; i<=nlstate+ndeath; i++)
                   3728:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3729:        po[i][j][h]=newm[i][j];
                   3730:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3731:       }
1.128     brouard  3732:     /*printf("h=%d ",h);*/
1.126     brouard  3733:   } /* end h */
1.267     brouard  3734:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3735:   return po;
                   3736: }
                   3737: 
1.217     brouard  3738: /************* Higher Back Matrix Product ***************/
1.218     brouard  3739: /* 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  3740: 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  3741: {
1.332     brouard  3742:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3743:      computes the transition matrix starting at age 'age' over
1.217     brouard  3744:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3745:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3746:      nhstepm*hstepm matrices.
                   3747:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3748:      (typically every 2 years instead of every month which is too big
1.217     brouard  3749:      for the memory).
1.218     brouard  3750:      Model is determined by parameters x and covariates have to be
1.266     brouard  3751:      included manually here. Then we use a call to bmij(x and cov)
                   3752:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3753:   */
1.217     brouard  3754: 
1.332     brouard  3755:   int i, j, d, h, k, k1;
1.266     brouard  3756:   double **out, cov[NCOVMAX+1], **bmij();
                   3757:   double **newm, ***newmm;
1.217     brouard  3758:   double agexact;
                   3759:   double agebegin, ageend;
1.222     brouard  3760:   double **oldm, **savm;
1.217     brouard  3761: 
1.266     brouard  3762:   newmm=po; /* To be saved */
                   3763:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3764:   /* Hstepm could be zero and should return the unit matrix */
                   3765:   for (i=1;i<=nlstate+ndeath;i++)
                   3766:     for (j=1;j<=nlstate+ndeath;j++){
                   3767:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3768:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3769:     }
                   3770:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3771:   for(h=1; h <=nhstepm; h++){
                   3772:     for(d=1; d <=hstepm; d++){
                   3773:       newm=savm;
                   3774:       /* Covariates have to be included here again */
                   3775:       cov[1]=1.;
1.271     brouard  3776:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3777:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3778:         /* Debug */
                   3779:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3780:       cov[2]=agexact;
1.332     brouard  3781:       if(nagesqr==1){
1.222     brouard  3782:        cov[3]= agexact*agexact;
1.332     brouard  3783:       }
                   3784:       /** New code */
                   3785:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3786:        if(Typevar[k1]==1){ /* A product with age */
                   3787:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3788:        }else{
1.332     brouard  3789:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3790:        }
1.332     brouard  3791:       }/* End of loop on model equation */
                   3792:       /** End of new code */
                   3793:   /** This was old code */
                   3794:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3795:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3796:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3797:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3798:       /*   /\* 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)); *\/ */
                   3799:       /* } */
                   3800:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3801:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3802:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3803:       /*       /\* 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]); *\/ */
                   3804:       /* } */
                   3805:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3806:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3807:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3808:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3809:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3810:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3811:       /*       } */
                   3812:       /*       /\* 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]); *\/ */
                   3813:       /* } */
                   3814:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3815:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3816:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3817:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3818:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3819:       /*         }else{ */
                   3820:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3821:       /*         } */
                   3822:       /*       }else{ */
                   3823:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3824:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3825:       /*         }else{ */
                   3826:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3827:       /*         } */
                   3828:       /*       } */
                   3829:       /* }                      */
                   3830:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3831:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3832: /** End of old code */
                   3833:       
1.218     brouard  3834:       /* Careful transposed matrix */
1.266     brouard  3835:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3836:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3837:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3838:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3839:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3840:       /* if((int)age == 70){ */
                   3841:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3842:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3843:       /*         printf("%d pmmij ",i); */
                   3844:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3845:       /*           printf("%f ",pmmij[i][j]); */
                   3846:       /*         } */
                   3847:       /*         printf(" oldm "); */
                   3848:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3849:       /*           printf("%f ",oldm[i][j]); */
                   3850:       /*         } */
                   3851:       /*         printf("\n"); */
                   3852:       /*       } */
                   3853:       /* } */
                   3854:       savm=oldm;
                   3855:       oldm=newm;
                   3856:     }
                   3857:     for(i=1; i<=nlstate+ndeath; i++)
                   3858:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3859:        po[i][j][h]=newm[i][j];
1.268     brouard  3860:        /* if(h==nhstepm) */
                   3861:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3862:       }
1.268     brouard  3863:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3864:   } /* end h */
1.268     brouard  3865:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3866:   return po;
                   3867: }
                   3868: 
                   3869: 
1.162     brouard  3870: #ifdef NLOPT
                   3871:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3872:   double fret;
                   3873:   double *xt;
                   3874:   int j;
                   3875:   myfunc_data *d2 = (myfunc_data *) pd;
                   3876: /* xt = (p1-1); */
                   3877:   xt=vector(1,n); 
                   3878:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3879: 
                   3880:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3881:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3882:   printf("Function = %.12lf ",fret);
                   3883:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3884:   printf("\n");
                   3885:  free_vector(xt,1,n);
                   3886:   return fret;
                   3887: }
                   3888: #endif
1.126     brouard  3889: 
                   3890: /*************** log-likelihood *************/
                   3891: double func( double *x)
                   3892: {
1.336     brouard  3893:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3894:   int ioffset=0;
1.339     brouard  3895:   int ipos=0,iposold=0,ncovv=0;
                   3896: 
1.340     brouard  3897:   double cotvarv, cotvarvold;
1.226     brouard  3898:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3899:   double **out;
                   3900:   double lli; /* Individual log likelihood */
                   3901:   int s1, s2;
1.228     brouard  3902:   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  3903: 
1.226     brouard  3904:   double bbh, survp;
                   3905:   double agexact;
1.336     brouard  3906:   double agebegin, ageend;
1.226     brouard  3907:   /*extern weight */
                   3908:   /* We are differentiating ll according to initial status */
                   3909:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3910:   /*for(i=1;i<imx;i++) 
                   3911:     printf(" %d\n",s[4][i]);
                   3912:   */
1.162     brouard  3913: 
1.226     brouard  3914:   ++countcallfunc;
1.162     brouard  3915: 
1.226     brouard  3916:   cov[1]=1.;
1.126     brouard  3917: 
1.226     brouard  3918:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3919:   ioffset=0;
1.226     brouard  3920:   if(mle==1){
                   3921:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3922:       /* Computes the values of the ncovmodel covariates of the model
                   3923:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3924:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3925:         to be observed in j being in i according to the model.
                   3926:       */
1.243     brouard  3927:       ioffset=2+nagesqr ;
1.233     brouard  3928:    /* Fixed */
1.336     brouard  3929:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3930:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3931:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3932:        /*  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  3933:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3934:        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  3935:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3936:       }
1.226     brouard  3937:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3938:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3939:         has been calculated etc */
                   3940:       /* For an individual i, wav[i] gives the number of effective waves */
                   3941:       /* We compute the contribution to Likelihood of each effective transition
                   3942:         mw[mi][i] is real wave of the mi th effectve wave */
                   3943:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3944:         s2=s[mw[mi+1][i]][i];
1.341     brouard  3945:         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  3946:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3947:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3948:       */
1.336     brouard  3949:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3950:       /* Wave varying (but not age varying) */
1.339     brouard  3951:        /* 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*\/ */
                   3952:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3953:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3954:        /* } */
1.340     brouard  3955:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3956:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3957:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   3958:          if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341     brouard  3959:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3960:          }else{ /* fixed covariate */
                   3961:            cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   3962:          }
1.339     brouard  3963:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3964:            cotvarvold=cotvarv;
                   3965:          }else{ /* A second product */
                   3966:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3967:          }
                   3968:          iposold=ipos;
1.340     brouard  3969:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  3970:        }
1.339     brouard  3971:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   3972:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3973:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3974:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3975:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3976:        /*   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]); */
                   3977:        /* } */
                   3978:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3979:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3980:        /*   /\* 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]); *\/ */
                   3981:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   3982:        /* } */
                   3983:        /* for products of time varying to be done */
1.234     brouard  3984:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3985:          for (j=1;j<=nlstate+ndeath;j++){
                   3986:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3987:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3988:          }
1.336     brouard  3989: 
                   3990:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3991:        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  3992:        for(d=0; d<dh[mi][i]; d++){
                   3993:          newm=savm;
                   3994:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3995:          cov[2]=agexact;
                   3996:          if(nagesqr==1)
                   3997:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3998:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3999:            if(!FixedV[Tvar[Tage[kk]]])
                   4000:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4001:            else
1.341     brouard  4002:              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  4003:          }
                   4004:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4005:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4006:          savm=oldm;
                   4007:          oldm=newm;
                   4008:        } /* end mult */
                   4009:        
                   4010:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4011:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4012:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4013:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4014:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4015:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4016:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4017:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4018:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4019:                                 * -stepm/2 to stepm/2 .
                   4020:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4021:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4022:                                 */
1.234     brouard  4023:        s1=s[mw[mi][i]][i];
                   4024:        s2=s[mw[mi+1][i]][i];
                   4025:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4026:        /* bias bh is positive if real duration
                   4027:         * is higher than the multiple of stepm and negative otherwise.
                   4028:         */
                   4029:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4030:        if( s2 > nlstate){ 
                   4031:          /* i.e. if s2 is a death state and if the date of death is known 
                   4032:             then the contribution to the likelihood is the probability to 
                   4033:             die between last step unit time and current  step unit time, 
                   4034:             which is also equal to probability to die before dh 
                   4035:             minus probability to die before dh-stepm . 
                   4036:             In version up to 0.92 likelihood was computed
                   4037:             as if date of death was unknown. Death was treated as any other
                   4038:             health state: the date of the interview describes the actual state
                   4039:             and not the date of a change in health state. The former idea was
                   4040:             to consider that at each interview the state was recorded
                   4041:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4042:             introduced the exact date of death then we should have modified
                   4043:             the contribution of an exact death to the likelihood. This new
                   4044:             contribution is smaller and very dependent of the step unit
                   4045:             stepm. It is no more the probability to die between last interview
                   4046:             and month of death but the probability to survive from last
                   4047:             interview up to one month before death multiplied by the
                   4048:             probability to die within a month. Thanks to Chris
                   4049:             Jackson for correcting this bug.  Former versions increased
                   4050:             mortality artificially. The bad side is that we add another loop
                   4051:             which slows down the processing. The difference can be up to 10%
                   4052:             lower mortality.
                   4053:          */
                   4054:          /* If, at the beginning of the maximization mostly, the
                   4055:             cumulative probability or probability to be dead is
                   4056:             constant (ie = 1) over time d, the difference is equal to
                   4057:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4058:             s1 at precedent wave, to be dead a month before current
                   4059:             wave is equal to probability, being at state s1 at
                   4060:             precedent wave, to be dead at mont of the current
                   4061:             wave. Then the observed probability (that this person died)
                   4062:             is null according to current estimated parameter. In fact,
                   4063:             it should be very low but not zero otherwise the log go to
                   4064:             infinity.
                   4065:          */
1.183     brouard  4066: /* #ifdef INFINITYORIGINAL */
                   4067: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4068: /* #else */
                   4069: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4070: /*         lli=log(mytinydouble); */
                   4071: /*       else */
                   4072: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4073: /* #endif */
1.226     brouard  4074:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4075:          
1.226     brouard  4076:        } else if  ( s2==-1 ) { /* alive */
                   4077:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4078:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4079:          /*survp += out[s1][j]; */
                   4080:          lli= log(survp);
                   4081:        }
1.336     brouard  4082:        /* else if  (s2==-4) {  */
                   4083:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4084:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4085:        /*   lli= log(survp);  */
                   4086:        /* }  */
                   4087:        /* else if  (s2==-5) {  */
                   4088:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4089:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4090:        /*   lli= log(survp);  */
                   4091:        /* }  */
1.226     brouard  4092:        else{
                   4093:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4094:          /*  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 */
                   4095:        } 
                   4096:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4097:        /*if(lli ==000.0)*/
1.340     brouard  4098:        /* 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  4099:        ipmx +=1;
                   4100:        sw += weight[i];
                   4101:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4102:        /* if (lli < log(mytinydouble)){ */
                   4103:        /*   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); */
                   4104:        /*   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]); */
                   4105:        /* } */
                   4106:       } /* end of wave */
                   4107:     } /* end of individual */
                   4108:   }  else if(mle==2){
                   4109:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4110:       ioffset=2+nagesqr ;
                   4111:       for (k=1; k<=ncovf;k++)
                   4112:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4113:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4114:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4115:          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  4116:        }
1.226     brouard  4117:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4118:          for (j=1;j<=nlstate+ndeath;j++){
                   4119:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4120:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4121:          }
                   4122:        for(d=0; d<=dh[mi][i]; d++){
                   4123:          newm=savm;
                   4124:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4125:          cov[2]=agexact;
                   4126:          if(nagesqr==1)
                   4127:            cov[3]= agexact*agexact;
                   4128:          for (kk=1; kk<=cptcovage;kk++) {
                   4129:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4130:          }
                   4131:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4132:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4133:          savm=oldm;
                   4134:          oldm=newm;
                   4135:        } /* end mult */
                   4136:       
                   4137:        s1=s[mw[mi][i]][i];
                   4138:        s2=s[mw[mi+1][i]][i];
                   4139:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4140:        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 */
                   4141:        ipmx +=1;
                   4142:        sw += weight[i];
                   4143:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4144:       } /* end of wave */
                   4145:     } /* end of individual */
                   4146:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4147:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4148:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4149:       for(mi=1; mi<= wav[i]-1; mi++){
                   4150:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4151:          for (j=1;j<=nlstate+ndeath;j++){
                   4152:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4153:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4154:          }
                   4155:        for(d=0; d<dh[mi][i]; d++){
                   4156:          newm=savm;
                   4157:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4158:          cov[2]=agexact;
                   4159:          if(nagesqr==1)
                   4160:            cov[3]= agexact*agexact;
                   4161:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4162:            if(!FixedV[Tvar[Tage[kk]]])
                   4163:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4164:            else
1.341     brouard  4165:              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  4166:          }
                   4167:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4168:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4169:          savm=oldm;
                   4170:          oldm=newm;
                   4171:        } /* end mult */
                   4172:       
                   4173:        s1=s[mw[mi][i]][i];
                   4174:        s2=s[mw[mi+1][i]][i];
                   4175:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4176:        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 */
                   4177:        ipmx +=1;
                   4178:        sw += weight[i];
                   4179:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4180:       } /* end of wave */
                   4181:     } /* end of individual */
                   4182:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4183:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4184:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4185:       for(mi=1; mi<= wav[i]-1; mi++){
                   4186:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4187:          for (j=1;j<=nlstate+ndeath;j++){
                   4188:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4189:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4190:          }
                   4191:        for(d=0; d<dh[mi][i]; d++){
                   4192:          newm=savm;
                   4193:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4194:          cov[2]=agexact;
                   4195:          if(nagesqr==1)
                   4196:            cov[3]= agexact*agexact;
                   4197:          for (kk=1; kk<=cptcovage;kk++) {
                   4198:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4199:          }
1.126     brouard  4200:        
1.226     brouard  4201:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4202:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4203:          savm=oldm;
                   4204:          oldm=newm;
                   4205:        } /* end mult */
                   4206:       
                   4207:        s1=s[mw[mi][i]][i];
                   4208:        s2=s[mw[mi+1][i]][i];
                   4209:        if( s2 > nlstate){ 
                   4210:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4211:        } else if  ( s2==-1 ) { /* alive */
                   4212:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4213:            survp += out[s1][j];
                   4214:          lli= log(survp);
                   4215:        }else{
                   4216:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4217:        }
                   4218:        ipmx +=1;
                   4219:        sw += weight[i];
                   4220:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.340     brouard  4221:        /* 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]); */
1.226     brouard  4222:       } /* end of wave */
                   4223:     } /* end of individual */
                   4224:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4225:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4226:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4227:       for(mi=1; mi<= wav[i]-1; mi++){
                   4228:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4229:          for (j=1;j<=nlstate+ndeath;j++){
                   4230:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4231:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4232:          }
                   4233:        for(d=0; d<dh[mi][i]; d++){
                   4234:          newm=savm;
                   4235:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4236:          cov[2]=agexact;
                   4237:          if(nagesqr==1)
                   4238:            cov[3]= agexact*agexact;
                   4239:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4240:            if(!FixedV[Tvar[Tage[kk]]])
                   4241:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4242:            else
1.341     brouard  4243:              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  4244:          }
1.126     brouard  4245:        
1.226     brouard  4246:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4247:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4248:          savm=oldm;
                   4249:          oldm=newm;
                   4250:        } /* end mult */
                   4251:       
                   4252:        s1=s[mw[mi][i]][i];
                   4253:        s2=s[mw[mi+1][i]][i];
                   4254:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4255:        ipmx +=1;
                   4256:        sw += weight[i];
                   4257:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4258:        /*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]);*/
                   4259:       } /* end of wave */
                   4260:     } /* end of individual */
                   4261:   } /* End of if */
                   4262:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4263:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4264:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4265:   return -l;
1.126     brouard  4266: }
                   4267: 
                   4268: /*************** log-likelihood *************/
                   4269: double funcone( double *x)
                   4270: {
1.228     brouard  4271:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4272:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4273:   int ioffset=0;
1.339     brouard  4274:   int ipos=0,iposold=0,ncovv=0;
                   4275: 
1.340     brouard  4276:   double cotvarv, cotvarvold;
1.131     brouard  4277:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4278:   double **out;
                   4279:   double lli; /* Individual log likelihood */
                   4280:   double llt;
                   4281:   int s1, s2;
1.228     brouard  4282:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4283: 
1.126     brouard  4284:   double bbh, survp;
1.187     brouard  4285:   double agexact;
1.214     brouard  4286:   double agebegin, ageend;
1.126     brouard  4287:   /*extern weight */
                   4288:   /* We are differentiating ll according to initial status */
                   4289:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4290:   /*for(i=1;i<imx;i++) 
                   4291:     printf(" %d\n",s[4][i]);
                   4292:   */
                   4293:   cov[1]=1.;
                   4294: 
                   4295:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4296:   ioffset=0;
                   4297:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4298:     /* Computes the values of the ncovmodel covariates of the model
                   4299:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4300:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4301:        to be observed in j being in i according to the model.
                   4302:     */
1.243     brouard  4303:     /* ioffset=2+nagesqr+cptcovage; */
                   4304:     ioffset=2+nagesqr;
1.232     brouard  4305:     /* Fixed */
1.224     brouard  4306:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4307:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4308:     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  4309:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4310:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4311:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4312:       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  4313: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4314: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4315: /*    cov[2+6]=covar[2][i]; V2  */
                   4316: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4317: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4318: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4319: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4320: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4321: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4322:     }
1.336     brouard  4323:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4324:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4325:         has been calculated etc */
                   4326:       /* For an individual i, wav[i] gives the number of effective waves */
                   4327:       /* We compute the contribution to Likelihood of each effective transition
                   4328:         mw[mi][i] is real wave of the mi th effectve wave */
                   4329:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4330:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4331:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4332:       */
                   4333:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4334:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4335:     /*   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?)*\/ */
                   4336:     /* } */
1.231     brouard  4337:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4338:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4339:     /* } */
1.225     brouard  4340:     
1.233     brouard  4341: 
                   4342:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4343:       /* 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 */
                   4344:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4345:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4346:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4347:       /* } */
                   4348:       
                   4349:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4350:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4351:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4352:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4353:       /* We need the position of the time varying or product in the model */
                   4354:       /* 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 */            
                   4355:       /* TvarVV gives the variable name */
1.340     brouard  4356:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4357:       *      k=         1   2     3     4         5        6        7       8        9
                   4358:       *  varying            1     2                                 3       4        5
                   4359:       *  ncovv              1     2                                3 4     5 6      7 8
                   4360:       *  TvarVV            V3     5                                1 3     3 5      1 5
                   4361:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4362:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4363:       * cotvar starts at ntv=2 (because of V3 V4)
                   4364:       */
                   4365:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4366:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4367:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4368:        if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341     brouard  4369:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.340     brouard  4370:        }else{ /* fixed covariate */
                   4371:          cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   4372:        }
1.339     brouard  4373:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4374:          cotvarvold=cotvarv;
                   4375:        }else{ /* A second product */
                   4376:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4377:        }
                   4378:        iposold=ipos;
1.340     brouard  4379:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4380:        /* For products */
                   4381:       }
                   4382:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4383:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4384:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4385:       /*       /\*           1  2   3      4      5                         *\/ */
                   4386:       /*       /\*itv           1                                           *\/ */
                   4387:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4388:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4389:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4390:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4391:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4392:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4393:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4394:       /*       /\* 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]); *\/ */
                   4395:       /* } */
1.232     brouard  4396:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4397:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4398:       /*       /\* 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]); *\/ */
                   4399:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4400:       /* } */
1.126     brouard  4401:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4402:        for (j=1;j<=nlstate+ndeath;j++){
                   4403:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4404:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4405:        }
1.214     brouard  4406:       
                   4407:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4408:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4409:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4410:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4411:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4412:          and mw[mi+1][i]. dh depends on stepm.*/
                   4413:        newm=savm;
1.247     brouard  4414:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4415:        cov[2]=agexact;
                   4416:        if(nagesqr==1)
                   4417:          cov[3]= agexact*agexact;
                   4418:        for (kk=1; kk<=cptcovage;kk++) {
                   4419:          if(!FixedV[Tvar[Tage[kk]]])
                   4420:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4421:          else
1.341     brouard  4422:            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  4423:        }
                   4424:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4425:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4426:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4427:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4428:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4429:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4430:        savm=oldm;
                   4431:        oldm=newm;
1.126     brouard  4432:       } /* end mult */
1.336     brouard  4433:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4434:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4435:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4436:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4437:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4438:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4439:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4440:         * probability in order to take into account the bias as a fraction of the way
                   4441:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4442:                                 * -stepm/2 to stepm/2 .
                   4443:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4444:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4445:                                 */
1.126     brouard  4446:       s1=s[mw[mi][i]][i];
                   4447:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4448:       /* if(s2==-1){ */
1.268     brouard  4449:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4450:       /*       /\* exit(1); *\/ */
                   4451:       /* } */
1.126     brouard  4452:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4453:       /* bias is positive if real duration
                   4454:        * is higher than the multiple of stepm and negative otherwise.
                   4455:        */
                   4456:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4457:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4458:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4459:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4460:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4461:        lli= log(survp);
1.126     brouard  4462:       }else if (mle==1){
1.242     brouard  4463:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4464:       } else if(mle==2){
1.242     brouard  4465:        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  4466:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4467:        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  4468:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4469:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4470:       } else{  /* mle=0 back to 1 */
1.242     brouard  4471:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4472:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4473:       } /* End of if */
                   4474:       ipmx +=1;
                   4475:       sw += weight[i];
                   4476:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342   ! brouard  4477:       /* Printing covariates values for each contribution for checking */
        !          4478:       /* printf(" s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",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  4479:       if(globpr){
1.246     brouard  4480:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4481:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4482:                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  4483:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.335     brouard  4484:  /*    printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4485:  /* %11.6f %11.6f %11.6f ", \ */
                   4486:  /*            num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4487:  /*            2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4488:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4489:          llt +=ll[k]*gipmx/gsw;
                   4490:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4491:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4492:        }
1.342   ! brouard  4493:        fprintf(ficresilk," %10.6f", -llt);
1.335     brouard  4494:        /* printf(" %10.6f\n", -llt); */
1.342   ! brouard  4495:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
        !          4496:          fprintf(ficresilk,"%09ld ", num[i]);
        !          4497:          for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
        !          4498:            fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
        !          4499:          }
        !          4500:          for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
        !          4501:            ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4502:            if(ipos!=iposold){ /* Not a product or first of a product */
        !          4503:              fprintf(ficresilk," %g",cov[ioffset+ipos]);
        !          4504:              /* printf(" %g",cov[ioffset+ipos]); */
        !          4505:            }else{
        !          4506:              fprintf(ficresilk,"*");
        !          4507:              /* printf("*"); */
        !          4508:            }
        !          4509:            iposold=ipos;
        !          4510:          }
        !          4511:          for (kk=1; kk<=cptcovage;kk++) {
        !          4512:            if(!FixedV[Tvar[Tage[kk]]]){
        !          4513:              fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]);
        !          4514:              /* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); */
        !          4515:            }else{
        !          4516:              fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
        !          4517:              /* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
        !          4518:            }
        !          4519:          }
        !          4520:          /* printf("\n"); */
        !          4521:        /* } /\*  End debugILK *\/ */
        !          4522:        fprintf(ficresilk,"\n");
        !          4523:       } /* End if globpr */
1.335     brouard  4524:     } /* end of wave */
                   4525:   } /* end of individual */
                   4526:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4527: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4528:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4529:   if(globpr==0){ /* First time we count the contributions and weights */
                   4530:     gipmx=ipmx;
                   4531:     gsw=sw;
                   4532:   }
1.232     brouard  4533: return -l;
1.126     brouard  4534: }
                   4535: 
                   4536: 
                   4537: /*************** function likelione ***********/
1.292     brouard  4538: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4539: {
                   4540:   /* This routine should help understanding what is done with 
                   4541:      the selection of individuals/waves and
                   4542:      to check the exact contribution to the likelihood.
                   4543:      Plotting could be done.
1.342   ! brouard  4544:   */
        !          4545:   void pstamp(FILE *ficres);
        !          4546:   int k, kf, kk, ncovv, iposold, ipos;
1.126     brouard  4547: 
                   4548:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4549:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4550:     strcat(fileresilk,fileresu);
1.126     brouard  4551:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4552:       printf("Problem with resultfile: %s\n", fileresilk);
                   4553:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4554:     }
1.342   ! brouard  4555:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4556:     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");
                   4557:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4558:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4559:     for(k=1; k<=nlstate; k++) 
                   4560:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342   ! brouard  4561:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
        !          4562: 
        !          4563:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
        !          4564:       for(kf=1;kf <= ncovf; kf++){
        !          4565:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
        !          4566:        /* printf("V%d",Tvar[TvarFind[kf]]); */
        !          4567:       }
        !          4568:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
        !          4569:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4570:        if(ipos!=iposold){ /* Not a product or first of a product */
        !          4571:          /* printf(" %d",ipos); */
        !          4572:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
        !          4573:        }else{
        !          4574:          /* printf("*"); */
        !          4575:          fprintf(ficresilk,"*");
        !          4576:            }
        !          4577:        iposold=ipos;
        !          4578:       }
        !          4579:       for (kk=1; kk<=cptcovage;kk++) {
        !          4580:        if(!FixedV[Tvar[Tage[kk]]]){
        !          4581:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
        !          4582:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
        !          4583:        }else{
        !          4584:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
        !          4585:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
        !          4586:        }
        !          4587:       }
        !          4588:     /* } /\* End if debugILK *\/ */
        !          4589:     /* printf("\n"); */
        !          4590:     fprintf(ficresilk,"\n");
        !          4591:   } /* End glogpri */
1.126     brouard  4592: 
1.292     brouard  4593:   *fretone=(*func)(p);
1.126     brouard  4594:   if(*globpri !=0){
                   4595:     fclose(ficresilk);
1.205     brouard  4596:     if (mle ==0)
                   4597:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4598:     else if(mle >=1)
                   4599:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4600:     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  4601:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4602:       
                   4603:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4604:       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> \
1.208     brouard  4605: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4606:     }
1.207     brouard  4607:     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.204     brouard  4608: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4609:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4610: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4611:     fflush(fichtm);
1.205     brouard  4612:   }
1.126     brouard  4613:   return;
                   4614: }
                   4615: 
                   4616: 
                   4617: /*********** Maximum Likelihood Estimation ***************/
                   4618: 
                   4619: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4620: {
1.319     brouard  4621:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4622:   double **xi;
                   4623:   double fret;
                   4624:   double fretone; /* Only one call to likelihood */
                   4625:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4626: 
                   4627: #ifdef NLOPT
                   4628:   int creturn;
                   4629:   nlopt_opt opt;
                   4630:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4631:   double *lb;
                   4632:   double minf; /* the minimum objective value, upon return */
                   4633:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4634:   myfunc_data dinst, *d = &dinst;
                   4635: #endif
                   4636: 
                   4637: 
1.126     brouard  4638:   xi=matrix(1,npar,1,npar);
                   4639:   for (i=1;i<=npar;i++)
                   4640:     for (j=1;j<=npar;j++)
                   4641:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4642:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4643:   strcpy(filerespow,"POW_"); 
1.126     brouard  4644:   strcat(filerespow,fileres);
                   4645:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4646:     printf("Problem with resultfile: %s\n", filerespow);
                   4647:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4648:   }
                   4649:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4650:   for (i=1;i<=nlstate;i++)
                   4651:     for(j=1;j<=nlstate+ndeath;j++)
                   4652:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4653:   fprintf(ficrespow,"\n");
1.162     brouard  4654: #ifdef POWELL
1.319     brouard  4655: #ifdef LINMINORIGINAL
                   4656: #else /* LINMINORIGINAL */
                   4657:   
                   4658:   flatdir=ivector(1,npar); 
                   4659:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4660: #endif /*LINMINORIGINAL */
                   4661: 
                   4662: #ifdef FLATSUP
                   4663:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4664:   /* reorganizing p by suppressing flat directions */
                   4665:   for(i=1, jk=1; i <=nlstate; i++){
                   4666:     for(k=1; k <=(nlstate+ndeath); k++){
                   4667:       if (k != i) {
                   4668:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4669:         if(flatdir[jk]==1){
                   4670:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4671:         }
                   4672:         for(j=1; j <=ncovmodel; j++){
                   4673:           printf("%12.7f ",p[jk]);
                   4674:           jk++; 
                   4675:         }
                   4676:         printf("\n");
                   4677:       }
                   4678:     }
                   4679:   }
                   4680: /* skipping */
                   4681:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4682:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4683:     for(k=1; k <=(nlstate+ndeath); k++){
                   4684:       if (k != i) {
                   4685:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4686:         if(flatdir[jk]==1){
                   4687:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4688:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4689:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4690:             /*q[jjk]=p[jk];*/
                   4691:           }
                   4692:         }else{
                   4693:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4694:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4695:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4696:             /*q[jjk]=p[jk];*/
                   4697:           }
                   4698:         }
                   4699:         printf("\n");
                   4700:       }
                   4701:       fflush(stdout);
                   4702:     }
                   4703:   }
                   4704:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4705: #else  /* FLATSUP */
1.126     brouard  4706:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4707: #endif  /* FLATSUP */
                   4708: 
                   4709: #ifdef LINMINORIGINAL
                   4710: #else
                   4711:       free_ivector(flatdir,1,npar); 
                   4712: #endif  /* LINMINORIGINAL*/
                   4713: #endif /* POWELL */
1.126     brouard  4714: 
1.162     brouard  4715: #ifdef NLOPT
                   4716: #ifdef NEWUOA
                   4717:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4718: #else
                   4719:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4720: #endif
                   4721:   lb=vector(0,npar-1);
                   4722:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4723:   nlopt_set_lower_bounds(opt, lb);
                   4724:   nlopt_set_initial_step1(opt, 0.1);
                   4725:   
                   4726:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4727:   d->function = func;
                   4728:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4729:   nlopt_set_min_objective(opt, myfunc, d);
                   4730:   nlopt_set_xtol_rel(opt, ftol);
                   4731:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4732:     printf("nlopt failed! %d\n",creturn); 
                   4733:   }
                   4734:   else {
                   4735:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4736:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4737:     iter=1; /* not equal */
                   4738:   }
                   4739:   nlopt_destroy(opt);
                   4740: #endif
1.319     brouard  4741: #ifdef FLATSUP
                   4742:   /* npared = npar -flatd/ncovmodel; */
                   4743:   /* xired= matrix(1,npared,1,npared); */
                   4744:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4745:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4746:   /* free_matrix(xire,1,npared,1,npared); */
                   4747: #else  /* FLATSUP */
                   4748: #endif /* FLATSUP */
1.126     brouard  4749:   free_matrix(xi,1,npar,1,npar);
                   4750:   fclose(ficrespow);
1.203     brouard  4751:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4752:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4753:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4754: 
                   4755: }
                   4756: 
                   4757: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4758: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4759: {
                   4760:   double  **a,**y,*x,pd;
1.203     brouard  4761:   /* double **hess; */
1.164     brouard  4762:   int i, j;
1.126     brouard  4763:   int *indx;
                   4764: 
                   4765:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4766:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4767:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4768:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4769:   double gompertz(double p[]);
1.203     brouard  4770:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4771: 
                   4772:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4773:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4774:   for (i=1;i<=npar;i++){
1.203     brouard  4775:     printf("%d-",i);fflush(stdout);
                   4776:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4777:    
                   4778:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4779:     
                   4780:     /*  printf(" %f ",p[i]);
                   4781:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4782:   }
                   4783:   
                   4784:   for (i=1;i<=npar;i++) {
                   4785:     for (j=1;j<=npar;j++)  {
                   4786:       if (j>i) { 
1.203     brouard  4787:        printf(".%d-%d",i,j);fflush(stdout);
                   4788:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4789:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4790:        
                   4791:        hess[j][i]=hess[i][j];    
                   4792:        /*printf(" %lf ",hess[i][j]);*/
                   4793:       }
                   4794:     }
                   4795:   }
                   4796:   printf("\n");
                   4797:   fprintf(ficlog,"\n");
                   4798: 
                   4799:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4800:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4801:   
                   4802:   a=matrix(1,npar,1,npar);
                   4803:   y=matrix(1,npar,1,npar);
                   4804:   x=vector(1,npar);
                   4805:   indx=ivector(1,npar);
                   4806:   for (i=1;i<=npar;i++)
                   4807:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4808:   ludcmp(a,npar,indx,&pd);
                   4809: 
                   4810:   for (j=1;j<=npar;j++) {
                   4811:     for (i=1;i<=npar;i++) x[i]=0;
                   4812:     x[j]=1;
                   4813:     lubksb(a,npar,indx,x);
                   4814:     for (i=1;i<=npar;i++){ 
                   4815:       matcov[i][j]=x[i];
                   4816:     }
                   4817:   }
                   4818: 
                   4819:   printf("\n#Hessian matrix#\n");
                   4820:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4821:   for (i=1;i<=npar;i++) { 
                   4822:     for (j=1;j<=npar;j++) { 
1.203     brouard  4823:       printf("%.6e ",hess[i][j]);
                   4824:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4825:     }
                   4826:     printf("\n");
                   4827:     fprintf(ficlog,"\n");
                   4828:   }
                   4829: 
1.203     brouard  4830:   /* printf("\n#Covariance matrix#\n"); */
                   4831:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4832:   /* for (i=1;i<=npar;i++) {  */
                   4833:   /*   for (j=1;j<=npar;j++) {  */
                   4834:   /*     printf("%.6e ",matcov[i][j]); */
                   4835:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4836:   /*   } */
                   4837:   /*   printf("\n"); */
                   4838:   /*   fprintf(ficlog,"\n"); */
                   4839:   /* } */
                   4840: 
1.126     brouard  4841:   /* Recompute Inverse */
1.203     brouard  4842:   /* for (i=1;i<=npar;i++) */
                   4843:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4844:   /* ludcmp(a,npar,indx,&pd); */
                   4845: 
                   4846:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4847: 
                   4848:   /* for (j=1;j<=npar;j++) { */
                   4849:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4850:   /*   x[j]=1; */
                   4851:   /*   lubksb(a,npar,indx,x); */
                   4852:   /*   for (i=1;i<=npar;i++){  */
                   4853:   /*     y[i][j]=x[i]; */
                   4854:   /*     printf("%.3e ",y[i][j]); */
                   4855:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4856:   /*   } */
                   4857:   /*   printf("\n"); */
                   4858:   /*   fprintf(ficlog,"\n"); */
                   4859:   /* } */
                   4860: 
                   4861:   /* Verifying the inverse matrix */
                   4862: #ifdef DEBUGHESS
                   4863:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4864: 
1.203     brouard  4865:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4866:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4867: 
                   4868:   for (j=1;j<=npar;j++) {
                   4869:     for (i=1;i<=npar;i++){ 
1.203     brouard  4870:       printf("%.2f ",y[i][j]);
                   4871:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4872:     }
                   4873:     printf("\n");
                   4874:     fprintf(ficlog,"\n");
                   4875:   }
1.203     brouard  4876: #endif
1.126     brouard  4877: 
                   4878:   free_matrix(a,1,npar,1,npar);
                   4879:   free_matrix(y,1,npar,1,npar);
                   4880:   free_vector(x,1,npar);
                   4881:   free_ivector(indx,1,npar);
1.203     brouard  4882:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4883: 
                   4884: 
                   4885: }
                   4886: 
                   4887: /*************** hessian matrix ****************/
                   4888: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4889: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4890:   int i;
                   4891:   int l=1, lmax=20;
1.203     brouard  4892:   double k1,k2, res, fx;
1.132     brouard  4893:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4894:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4895:   int k=0,kmax=10;
                   4896:   double l1;
                   4897: 
                   4898:   fx=func(x);
                   4899:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4900:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4901:     l1=pow(10,l);
                   4902:     delts=delt;
                   4903:     for(k=1 ; k <kmax; k=k+1){
                   4904:       delt = delta*(l1*k);
                   4905:       p2[theta]=x[theta] +delt;
1.145     brouard  4906:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4907:       p2[theta]=x[theta]-delt;
                   4908:       k2=func(p2)-fx;
                   4909:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4910:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4911:       
1.203     brouard  4912: #ifdef DEBUGHESSII
1.126     brouard  4913:       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);
                   4914:       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);
                   4915: #endif
                   4916:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4917:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4918:        k=kmax;
                   4919:       }
                   4920:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4921:        k=kmax; l=lmax*10;
1.126     brouard  4922:       }
                   4923:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4924:        delts=delt;
                   4925:       }
1.203     brouard  4926:     } /* End loop k */
1.126     brouard  4927:   }
                   4928:   delti[theta]=delts;
                   4929:   return res; 
                   4930:   
                   4931: }
                   4932: 
1.203     brouard  4933: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4934: {
                   4935:   int i;
1.164     brouard  4936:   int l=1, lmax=20;
1.126     brouard  4937:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4938:   double p2[MAXPARM+1];
1.203     brouard  4939:   int k, kmax=1;
                   4940:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4941: 
                   4942:   int firstime=0;
1.203     brouard  4943:   
1.126     brouard  4944:   fx=func(x);
1.203     brouard  4945:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4946:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4947:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4948:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4949:     k1=func(p2)-fx;
                   4950:   
1.203     brouard  4951:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4952:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4953:     k2=func(p2)-fx;
                   4954:   
1.203     brouard  4955:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4956:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4957:     k3=func(p2)-fx;
                   4958:   
1.203     brouard  4959:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4960:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4961:     k4=func(p2)-fx;
1.203     brouard  4962:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4963:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4964:       firstime=1;
1.203     brouard  4965:       kmax=kmax+10;
1.208     brouard  4966:     }
                   4967:     if(kmax >=10 || firstime ==1){
1.246     brouard  4968:       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);
                   4969:       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  4970:       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);
                   4971:       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);
                   4972:     }
                   4973: #ifdef DEBUGHESSIJ
                   4974:     v1=hess[thetai][thetai];
                   4975:     v2=hess[thetaj][thetaj];
                   4976:     cv12=res;
                   4977:     /* Computing eigen value of Hessian matrix */
                   4978:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4979:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4980:     if ((lc2 <0) || (lc1 <0) ){
                   4981:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4982:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4983:       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);
                   4984:       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);
                   4985:     }
1.126     brouard  4986: #endif
                   4987:   }
                   4988:   return res;
                   4989: }
                   4990: 
1.203     brouard  4991:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4992: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4993: /* { */
                   4994: /*   int i; */
                   4995: /*   int l=1, lmax=20; */
                   4996: /*   double k1,k2,k3,k4,res,fx; */
                   4997: /*   double p2[MAXPARM+1]; */
                   4998: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4999: /*   int k=0,kmax=10; */
                   5000: /*   double l1; */
                   5001:   
                   5002: /*   fx=func(x); */
                   5003: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5004: /*     l1=pow(10,l); */
                   5005: /*     delts=delt; */
                   5006: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5007: /*       delt = delti*(l1*k); */
                   5008: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5009: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5010: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5011: /*       k1=func(p2)-fx; */
                   5012:       
                   5013: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5014: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5015: /*       k2=func(p2)-fx; */
                   5016:       
                   5017: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5018: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5019: /*       k3=func(p2)-fx; */
                   5020:       
                   5021: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5022: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5023: /*       k4=func(p2)-fx; */
                   5024: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5025: /* #ifdef DEBUGHESSIJ */
                   5026: /*       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); */
                   5027: /*       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); */
                   5028: /* #endif */
                   5029: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5030: /*     k=kmax; */
                   5031: /*       } */
                   5032: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5033: /*     k=kmax; l=lmax*10; */
                   5034: /*       } */
                   5035: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5036: /*     delts=delt; */
                   5037: /*       } */
                   5038: /*     } /\* End loop k *\/ */
                   5039: /*   } */
                   5040: /*   delti[theta]=delts; */
                   5041: /*   return res;  */
                   5042: /* } */
                   5043: 
                   5044: 
1.126     brouard  5045: /************** Inverse of matrix **************/
                   5046: void ludcmp(double **a, int n, int *indx, double *d) 
                   5047: { 
                   5048:   int i,imax,j,k; 
                   5049:   double big,dum,sum,temp; 
                   5050:   double *vv; 
                   5051:  
                   5052:   vv=vector(1,n); 
                   5053:   *d=1.0; 
                   5054:   for (i=1;i<=n;i++) { 
                   5055:     big=0.0; 
                   5056:     for (j=1;j<=n;j++) 
                   5057:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5058:     if (big == 0.0){
                   5059:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5060:       for (j=1;j<=n;j++) {
                   5061:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5062:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5063:       }
                   5064:       fflush(ficlog);
                   5065:       fclose(ficlog);
                   5066:       nrerror("Singular matrix in routine ludcmp"); 
                   5067:     }
1.126     brouard  5068:     vv[i]=1.0/big; 
                   5069:   } 
                   5070:   for (j=1;j<=n;j++) { 
                   5071:     for (i=1;i<j;i++) { 
                   5072:       sum=a[i][j]; 
                   5073:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5074:       a[i][j]=sum; 
                   5075:     } 
                   5076:     big=0.0; 
                   5077:     for (i=j;i<=n;i++) { 
                   5078:       sum=a[i][j]; 
                   5079:       for (k=1;k<j;k++) 
                   5080:        sum -= a[i][k]*a[k][j]; 
                   5081:       a[i][j]=sum; 
                   5082:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5083:        big=dum; 
                   5084:        imax=i; 
                   5085:       } 
                   5086:     } 
                   5087:     if (j != imax) { 
                   5088:       for (k=1;k<=n;k++) { 
                   5089:        dum=a[imax][k]; 
                   5090:        a[imax][k]=a[j][k]; 
                   5091:        a[j][k]=dum; 
                   5092:       } 
                   5093:       *d = -(*d); 
                   5094:       vv[imax]=vv[j]; 
                   5095:     } 
                   5096:     indx[j]=imax; 
                   5097:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5098:     if (j != n) { 
                   5099:       dum=1.0/(a[j][j]); 
                   5100:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5101:     } 
                   5102:   } 
                   5103:   free_vector(vv,1,n);  /* Doesn't work */
                   5104: ;
                   5105: } 
                   5106: 
                   5107: void lubksb(double **a, int n, int *indx, double b[]) 
                   5108: { 
                   5109:   int i,ii=0,ip,j; 
                   5110:   double sum; 
                   5111:  
                   5112:   for (i=1;i<=n;i++) { 
                   5113:     ip=indx[i]; 
                   5114:     sum=b[ip]; 
                   5115:     b[ip]=b[i]; 
                   5116:     if (ii) 
                   5117:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5118:     else if (sum) ii=i; 
                   5119:     b[i]=sum; 
                   5120:   } 
                   5121:   for (i=n;i>=1;i--) { 
                   5122:     sum=b[i]; 
                   5123:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5124:     b[i]=sum/a[i][i]; 
                   5125:   } 
                   5126: } 
                   5127: 
                   5128: void pstamp(FILE *fichier)
                   5129: {
1.196     brouard  5130:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5131: }
                   5132: 
1.297     brouard  5133: void date2dmy(double date,double *day, double *month, double *year){
                   5134:   double yp=0., yp1=0., yp2=0.;
                   5135:   
                   5136:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5137:                        fractional in yp1 */
                   5138:   *year=yp;
                   5139:   yp2=modf((yp1*12),&yp);
                   5140:   *month=yp;
                   5141:   yp1=modf((yp2*30.5),&yp);
                   5142:   *day=yp;
                   5143:   if(*day==0) *day=1;
                   5144:   if(*month==0) *month=1;
                   5145: }
                   5146: 
1.253     brouard  5147: 
                   5148: 
1.126     brouard  5149: /************ Frequencies ********************/
1.251     brouard  5150: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5151:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5152:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5153: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5154:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5155:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5156:   int iind=0, iage=0;
                   5157:   int mi; /* Effective wave */
                   5158:   int first;
                   5159:   double ***freq; /* Frequencies */
1.268     brouard  5160:   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 */
                   5161:   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  5162:   double *meanq, *stdq, *idq;
1.226     brouard  5163:   double **meanqt;
                   5164:   double *pp, **prop, *posprop, *pospropt;
                   5165:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5166:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5167:   double agebegin, ageend;
                   5168:     
                   5169:   pp=vector(1,nlstate);
1.251     brouard  5170:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5171:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5172:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5173:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5174:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5175:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5176:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5177:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5178:   strcpy(fileresp,"P_");
                   5179:   strcat(fileresp,fileresu);
                   5180:   /*strcat(fileresphtm,fileresu);*/
                   5181:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5182:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5183:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5184:     exit(0);
                   5185:   }
1.240     brouard  5186:   
1.226     brouard  5187:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5188:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5189:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5190:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5191:     fflush(ficlog);
                   5192:     exit(70); 
                   5193:   }
                   5194:   else{
                   5195:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5196: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5197: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5198:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5199:   }
1.319     brouard  5200:   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  5201:   
1.226     brouard  5202:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5203:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5204:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5205:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5206:     fflush(ficlog);
                   5207:     exit(70); 
1.240     brouard  5208:   } else{
1.226     brouard  5209:     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  5210: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5211: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5212:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5213:   }
1.319     brouard  5214:   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  5215:   
1.253     brouard  5216:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5217:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5218:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5219:   j1=0;
1.126     brouard  5220:   
1.227     brouard  5221:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5222:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5223:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5224:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5225:   
                   5226:   
1.226     brouard  5227:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5228:      reference=low_education V1=0,V2=0
                   5229:      med_educ                V1=1 V2=0, 
                   5230:      high_educ               V1=0 V2=1
1.330     brouard  5231:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5232:   */
1.249     brouard  5233:   dateintsum=0;
                   5234:   k2cpt=0;
                   5235: 
1.253     brouard  5236:   if(cptcoveff == 0 )
1.265     brouard  5237:     nl=1;  /* Constant and age model only */
1.253     brouard  5238:   else
                   5239:     nl=2;
1.265     brouard  5240: 
                   5241:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5242:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5243:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5244:    *     freq[s1][s2][iage] =0.
                   5245:    *     Loop on iind
                   5246:    *       ++freq[s1][s2][iage] weighted
                   5247:    *     end iind
                   5248:    *     if covariate and j!0
                   5249:    *       headers Variable on one line
                   5250:    *     endif cov j!=0
                   5251:    *     header of frequency table by age
                   5252:    *     Loop on age
                   5253:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5254:    *       pos+=freq[s1][s2][iage] weighted
                   5255:    *       Loop on s1 initial state
                   5256:    *         fprintf(ficresp
                   5257:    *       end s1
                   5258:    *     end age
                   5259:    *     if j!=0 computes starting values
                   5260:    *     end compute starting values
                   5261:    *   end j1
                   5262:    * end nl 
                   5263:    */
1.253     brouard  5264:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5265:     if(nj==1)
                   5266:       j=0;  /* First pass for the constant */
1.265     brouard  5267:     else{
1.335     brouard  5268:       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  5269:     }
1.251     brouard  5270:     first=1;
1.332     brouard  5271:     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  5272:       posproptt=0.;
1.330     brouard  5273:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5274:        scanf("%d", i);*/
                   5275:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5276:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5277:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5278:            freq[i][s2][m]=0;
1.251     brouard  5279:       
                   5280:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5281:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5282:          prop[i][m]=0;
                   5283:        posprop[i]=0;
                   5284:        pospropt[i]=0;
                   5285:       }
1.283     brouard  5286:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5287:         idq[z1]=0.;
                   5288:         meanq[z1]=0.;
                   5289:         stdq[z1]=0.;
1.283     brouard  5290:       }
                   5291:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5292:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5293:       /*         meanqt[m][z1]=0.; */
                   5294:       /*       } */
                   5295:       /* }       */
1.251     brouard  5296:       /* dateintsum=0; */
                   5297:       /* k2cpt=0; */
                   5298:       
1.265     brouard  5299:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5300:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5301:        bool=1;
                   5302:        if(j !=0){
                   5303:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5304:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5305:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5306:                /* if(Tvaraff[z1] ==-20){ */
                   5307:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5308:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5309:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5310:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5311:                /* 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); */
                   5312:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5313:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5314:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5315:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5316:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5317:                  /* 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", */
                   5318:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5319:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5320:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5321:                } /* Onlyf fixed */
                   5322:              } /* end z1 */
1.335     brouard  5323:            } /* cptcoveff > 0 */
1.251     brouard  5324:          } /* end any */
                   5325:        }/* end j==0 */
1.265     brouard  5326:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5327:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5328:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5329:            m=mw[mi][iind];
                   5330:            if(j!=0){
                   5331:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5332:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5333:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5334:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5335:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5336:                    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  5337:                                                                                      value is -1, we don't select. It differs from the 
                   5338:                                                                                      constant and age model which counts them. */
                   5339:                      bool=0; /* not selected */
                   5340:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5341:                    /* i1=Tvaraff[z1]; */
                   5342:                    /* i2=TnsdVar[i1]; */
                   5343:                    /* i3=nbcode[i1][i2]; */
                   5344:                    /* i4=covar[i1][iind]; */
                   5345:                    /* if(i4 != i3){ */
                   5346:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5347:                      bool=0;
                   5348:                    }
                   5349:                  }
                   5350:                }
                   5351:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5352:            } /* end j==0 */
                   5353:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5354:            if(bool==1){ /*Selected */
1.251     brouard  5355:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5356:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5357:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5358:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5359:              if(m >=firstpass && m <=lastpass){
                   5360:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5361:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5362:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5363:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5364:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5365:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5366:                if (m<lastpass) {
                   5367:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5368:                  /*   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]); */
                   5369:                  if(s[m][iind]==-1)
                   5370:                    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.));
                   5371:                  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  5372:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5373:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5374:                      idq[z1]=idq[z1]+weight[iind];
                   5375:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5376:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5377:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5378:                    }
1.284     brouard  5379:                  }
1.251     brouard  5380:                  /* if((int)agev[m][iind] == 55) */
                   5381:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5382:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5383:                  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  5384:                }
1.251     brouard  5385:              } /* end if between passes */  
                   5386:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5387:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5388:                k2cpt++;
                   5389:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5390:              }
1.251     brouard  5391:            }else{
                   5392:              bool=1;
                   5393:            }/* end bool 2 */
                   5394:          } /* end m */
1.284     brouard  5395:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5396:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5397:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5398:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5399:          /* } */
1.251     brouard  5400:        } /* end bool */
                   5401:       } /* end iind = 1 to imx */
1.319     brouard  5402:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5403:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5404:       
                   5405:       
                   5406:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5407:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5408:         pstamp(ficresp);
1.335     brouard  5409:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5410:         pstamp(ficresp);
1.251     brouard  5411:        printf( "\n#********** Variable "); 
                   5412:        fprintf(ficresp, "\n#********** Variable "); 
                   5413:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5414:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5415:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5416:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5417:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5418:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5419:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5420:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5421:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5422:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5423:          }else{
1.330     brouard  5424:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5425:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5426:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5427:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5428:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5429:          }
                   5430:        }
                   5431:        printf( "**********\n#");
                   5432:        fprintf(ficresp, "**********\n#");
                   5433:        fprintf(ficresphtm, "**********</h3>\n");
                   5434:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5435:        fprintf(ficlog, "**********\n");
                   5436:       }
1.284     brouard  5437:       /*
                   5438:        Printing means of quantitative variables if any
                   5439:       */
                   5440:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5441:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5442:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5443:        if(weightopt==1){
                   5444:          printf(" Weighted mean and standard deviation of");
                   5445:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5446:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5447:        }
1.311     brouard  5448:        /* mu = \frac{w x}{\sum w}
                   5449:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5450:        */
                   5451:        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]));
                   5452:        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]));
                   5453:        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  5454:       }
                   5455:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5456:       /*       for(m=1;m<=lastpass;m++){ */
                   5457:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5458:       /*   } */
                   5459:       /* } */
1.283     brouard  5460: 
1.251     brouard  5461:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5462:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5463:         fprintf(ficresp, " Age");
1.335     brouard  5464:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5465:          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]]);
                   5466:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5467:        }
1.251     brouard  5468:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5469:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5470:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5471:       }
1.335     brouard  5472:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5473:       fprintf(ficresphtm, "\n");
                   5474:       
                   5475:       /* Header of frequency table by age */
                   5476:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5477:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5478:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5479:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5480:          if(s2!=0 && m!=0)
                   5481:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5482:        }
1.226     brouard  5483:       }
1.251     brouard  5484:       fprintf(ficresphtmfr, "\n");
                   5485:     
                   5486:       /* For each age */
                   5487:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5488:        fprintf(ficresphtm,"<tr>");
                   5489:        if(iage==iagemax+1){
                   5490:          fprintf(ficlog,"1");
                   5491:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5492:        }else if(iage==iagemax+2){
                   5493:          fprintf(ficlog,"0");
                   5494:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5495:        }else if(iage==iagemax+3){
                   5496:          fprintf(ficlog,"Total");
                   5497:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5498:        }else{
1.240     brouard  5499:          if(first==1){
1.251     brouard  5500:            first=0;
                   5501:            printf("See log file for details...\n");
                   5502:          }
                   5503:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5504:          fprintf(ficlog,"Age %d", iage);
                   5505:        }
1.265     brouard  5506:        for(s1=1; s1 <=nlstate ; s1++){
                   5507:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5508:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5509:        }
1.265     brouard  5510:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5511:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5512:            pos += freq[s1][m][iage];
                   5513:          if(pp[s1]>=1.e-10){
1.251     brouard  5514:            if(first==1){
1.265     brouard  5515:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5516:            }
1.265     brouard  5517:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5518:          }else{
                   5519:            if(first==1)
1.265     brouard  5520:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5521:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5522:          }
                   5523:        }
                   5524:       
1.265     brouard  5525:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5526:          /* posprop[s1]=0; */
                   5527:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5528:            pp[s1] += freq[s1][m][iage];
                   5529:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5530:       
                   5531:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5532:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5533:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5534:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5535:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5536:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5537:        }
                   5538:        
                   5539:        /* Writing ficresp */
1.335     brouard  5540:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5541:           if( iage <= iagemax){
                   5542:            fprintf(ficresp," %d",iage);
                   5543:           }
                   5544:         }else if( nj==2){
                   5545:           if( iage <= iagemax){
                   5546:            fprintf(ficresp," %d",iage);
1.335     brouard  5547:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5548:           }
1.240     brouard  5549:        }
1.265     brouard  5550:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5551:          if(pos>=1.e-5){
1.251     brouard  5552:            if(first==1)
1.265     brouard  5553:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5554:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5555:          }else{
                   5556:            if(first==1)
1.265     brouard  5557:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5558:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5559:          }
                   5560:          if( iage <= iagemax){
                   5561:            if(pos>=1.e-5){
1.335     brouard  5562:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5563:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5564:               }else if( nj==2){
                   5565:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5566:               }
                   5567:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5568:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5569:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5570:            } else{
1.335     brouard  5571:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5572:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5573:            }
1.240     brouard  5574:          }
1.265     brouard  5575:          pospropt[s1] +=posprop[s1];
                   5576:        } /* end loop s1 */
1.251     brouard  5577:        /* pospropt=0.; */
1.265     brouard  5578:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5579:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5580:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5581:              if(first==1){
1.265     brouard  5582:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5583:              }
1.265     brouard  5584:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5585:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5586:            }
1.265     brouard  5587:            if(s1!=0 && m!=0)
                   5588:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5589:          }
1.265     brouard  5590:        } /* end loop s1 */
1.251     brouard  5591:        posproptt=0.; 
1.265     brouard  5592:        for(s1=1; s1 <=nlstate; s1++){
                   5593:          posproptt += pospropt[s1];
1.251     brouard  5594:        }
                   5595:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5596:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5597:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5598:          if(iage <= iagemax)
                   5599:            fprintf(ficresp,"\n");
1.240     brouard  5600:        }
1.251     brouard  5601:        if(first==1)
                   5602:          printf("Others in log...\n");
                   5603:        fprintf(ficlog,"\n");
                   5604:       } /* end loop age iage */
1.265     brouard  5605:       
1.251     brouard  5606:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5607:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5608:        if(posproptt < 1.e-5){
1.265     brouard  5609:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5610:        }else{
1.265     brouard  5611:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5612:        }
1.226     brouard  5613:       }
1.251     brouard  5614:       fprintf(ficresphtm,"</tr>\n");
                   5615:       fprintf(ficresphtm,"</table>\n");
                   5616:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5617:       if(posproptt < 1.e-5){
1.251     brouard  5618:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5619:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5620:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5621:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5622:        invalidvarcomb[j1]=1;
1.226     brouard  5623:       }else{
1.338     brouard  5624:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5625:        invalidvarcomb[j1]=0;
1.226     brouard  5626:       }
1.251     brouard  5627:       fprintf(ficresphtmfr,"</table>\n");
                   5628:       fprintf(ficlog,"\n");
                   5629:       if(j!=0){
                   5630:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5631:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5632:          for(k=1; k <=(nlstate+ndeath); k++){
                   5633:            if (k != i) {
1.265     brouard  5634:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5635:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5636:                  if(j1==1){ /* All dummy covariates to zero */
                   5637:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5638:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5639:                    printf("%d%d ",i,k);
                   5640:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5641:                    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]));
                   5642:                    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]));
                   5643:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5644:                  }
1.253     brouard  5645:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5646:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5647:                    x[iage]= (double)iage;
                   5648:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5649:                    /* 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  5650:                  }
1.268     brouard  5651:                  /* Some are not finite, but linreg will ignore these ages */
                   5652:                  no=0;
1.253     brouard  5653:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5654:                  pstart[s1]=b;
                   5655:                  pstart[s1-1]=a;
1.252     brouard  5656:                }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 */ 
                   5657:                  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]);
                   5658:                  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  5659:                  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  5660:                  printf("%d%d ",i,k);
                   5661:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5662:                  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  5663:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5664:                  ;
                   5665:                }
                   5666:                /* printf("%12.7f )", param[i][jj][k]); */
                   5667:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5668:                s1++; 
1.251     brouard  5669:              } /* end jj */
                   5670:            } /* end k!= i */
                   5671:          } /* end k */
1.265     brouard  5672:        } /* end i, s1 */
1.251     brouard  5673:       } /* end j !=0 */
                   5674:     } /* end selected combination of covariate j1 */
                   5675:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5676:       printf("#Freqsummary: Starting values for the constants:\n");
                   5677:       fprintf(ficlog,"\n");
1.265     brouard  5678:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5679:        for(k=1; k <=(nlstate+ndeath); k++){
                   5680:          if (k != i) {
                   5681:            printf("%d%d ",i,k);
                   5682:            fprintf(ficlog,"%d%d ",i,k);
                   5683:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5684:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5685:              if(jj==1){ /* Age has to be done */
1.265     brouard  5686:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5687:                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]));
                   5688:                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  5689:              }
                   5690:              /* printf("%12.7f )", param[i][jj][k]); */
                   5691:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5692:              s1++; 
1.250     brouard  5693:            }
1.251     brouard  5694:            printf("\n");
                   5695:            fprintf(ficlog,"\n");
1.250     brouard  5696:          }
                   5697:        }
1.284     brouard  5698:       } /* end of state i */
1.251     brouard  5699:       printf("#Freqsummary\n");
                   5700:       fprintf(ficlog,"\n");
1.265     brouard  5701:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5702:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5703:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5704:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5705:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5706:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5707:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5708:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5709:          /* } */
                   5710:        }
1.265     brouard  5711:       } /* end loop s1 */
1.251     brouard  5712:       
                   5713:       printf("\n");
                   5714:       fprintf(ficlog,"\n");
                   5715:     } /* end j=0 */
1.249     brouard  5716:   } /* end j */
1.252     brouard  5717: 
1.253     brouard  5718:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5719:     for(i=1, jk=1; i <=nlstate; i++){
                   5720:       for(j=1; j <=nlstate+ndeath; j++){
                   5721:        if(j!=i){
                   5722:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5723:          printf("%1d%1d",i,j);
                   5724:          fprintf(ficparo,"%1d%1d",i,j);
                   5725:          for(k=1; k<=ncovmodel;k++){
                   5726:            /*    printf(" %lf",param[i][j][k]); */
                   5727:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5728:            p[jk]=pstart[jk];
                   5729:            printf(" %f ",pstart[jk]);
                   5730:            fprintf(ficparo," %f ",pstart[jk]);
                   5731:            jk++;
                   5732:          }
                   5733:          printf("\n");
                   5734:          fprintf(ficparo,"\n");
                   5735:        }
                   5736:       }
                   5737:     }
                   5738:   } /* end mle=-2 */
1.226     brouard  5739:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5740:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5741:   
1.226     brouard  5742:   fclose(ficresp);
                   5743:   fclose(ficresphtm);
                   5744:   fclose(ficresphtmfr);
1.283     brouard  5745:   free_vector(idq,1,nqfveff);
1.226     brouard  5746:   free_vector(meanq,1,nqfveff);
1.284     brouard  5747:   free_vector(stdq,1,nqfveff);
1.226     brouard  5748:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5749:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5750:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5751:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5752:   free_vector(pospropt,1,nlstate);
                   5753:   free_vector(posprop,1,nlstate);
1.251     brouard  5754:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5755:   free_vector(pp,1,nlstate);
                   5756:   /* End of freqsummary */
                   5757: }
1.126     brouard  5758: 
1.268     brouard  5759: /* Simple linear regression */
                   5760: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5761: 
                   5762:   /* y=a+bx regression */
                   5763:   double   sumx = 0.0;                        /* sum of x                      */
                   5764:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5765:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5766:   double   sumy = 0.0;                        /* sum of y                      */
                   5767:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5768:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5769:   double yhat;
                   5770:   
                   5771:   double denom=0;
                   5772:   int i;
                   5773:   int ne=*no;
                   5774:   
                   5775:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5776:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5777:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5778:       continue;
                   5779:     }
                   5780:     ne=ne+1;
                   5781:     sumx  += x[i];       
                   5782:     sumx2 += x[i]*x[i];  
                   5783:     sumxy += x[i] * y[i];
                   5784:     sumy  += y[i];      
                   5785:     sumy2 += y[i]*y[i]; 
                   5786:     denom = (ne * sumx2 - sumx*sumx);
                   5787:     /* 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); */
                   5788:   } 
                   5789:   
                   5790:   denom = (ne * sumx2 - sumx*sumx);
                   5791:   if (denom == 0) {
                   5792:     // vertical, slope m is infinity
                   5793:     *b = INFINITY;
                   5794:     *a = 0;
                   5795:     if (r) *r = 0;
                   5796:     return 1;
                   5797:   }
                   5798:   
                   5799:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5800:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5801:   if (r!=NULL) {
                   5802:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5803:       sqrt((sumx2 - sumx*sumx/ne) *
                   5804:           (sumy2 - sumy*sumy/ne));
                   5805:   }
                   5806:   *no=ne;
                   5807:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5808:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5809:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5810:       continue;
                   5811:     }
                   5812:     ne=ne+1;
                   5813:     yhat = y[i] - *a -*b* x[i];
                   5814:     sume2  += yhat * yhat ;       
                   5815:     
                   5816:     denom = (ne * sumx2 - sumx*sumx);
                   5817:     /* 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); */
                   5818:   } 
                   5819:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5820:   *sa= *sb * sqrt(sumx2/ne);
                   5821:   
                   5822:   return 0; 
                   5823: }
                   5824: 
1.126     brouard  5825: /************ Prevalence ********************/
1.227     brouard  5826: 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)
                   5827: {  
                   5828:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5829:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5830:      We still use firstpass and lastpass as another selection.
                   5831:   */
1.126     brouard  5832:  
1.227     brouard  5833:   int i, m, jk, j1, bool, z1,j, iv;
                   5834:   int mi; /* Effective wave */
                   5835:   int iage;
                   5836:   double agebegin, ageend;
                   5837: 
                   5838:   double **prop;
                   5839:   double posprop; 
                   5840:   double  y2; /* in fractional years */
                   5841:   int iagemin, iagemax;
                   5842:   int first; /** to stop verbosity which is redirected to log file */
                   5843: 
                   5844:   iagemin= (int) agemin;
                   5845:   iagemax= (int) agemax;
                   5846:   /*pp=vector(1,nlstate);*/
1.251     brouard  5847:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5848:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5849:   j1=0;
1.222     brouard  5850:   
1.227     brouard  5851:   /*j=cptcoveff;*/
                   5852:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5853:   
1.288     brouard  5854:   first=0;
1.335     brouard  5855:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5856:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5857:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5858:        prop[i][iage]=0.0;
                   5859:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5860:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5861:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5862:     
                   5863:     for (i=1; i<=imx; i++) { /* Each individual */
                   5864:       bool=1;
                   5865:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5866:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5867:        m=mw[mi][i];
                   5868:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5869:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5870:        for (z1=1; z1<=cptcoveff; z1++){
                   5871:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5872:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5873:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5874:              bool=0;
                   5875:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5876:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5877:              bool=0;
                   5878:            }
                   5879:        }
                   5880:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5881:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5882:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5883:          if(m >=firstpass && m <=lastpass){
                   5884:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5885:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5886:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5887:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5888:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5889:                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); 
                   5890:                exit(1);
                   5891:              }
                   5892:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5893:                /*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]]);*/
                   5894:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5895:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5896:              } /* end valid statuses */ 
                   5897:            } /* end selection of dates */
                   5898:          } /* end selection of waves */
                   5899:        } /* end bool */
                   5900:       } /* end wave */
                   5901:     } /* end individual */
                   5902:     for(i=iagemin; i <= iagemax+3; i++){  
                   5903:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5904:        posprop += prop[jk][i]; 
                   5905:       } 
                   5906:       
                   5907:       for(jk=1; jk <=nlstate ; jk++){      
                   5908:        if( i <=  iagemax){ 
                   5909:          if(posprop>=1.e-5){ 
                   5910:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5911:          } else{
1.288     brouard  5912:            if(!first){
                   5913:              first=1;
1.266     brouard  5914:              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]);
                   5915:            }else{
1.288     brouard  5916:              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  5917:            }
                   5918:          }
                   5919:        } 
                   5920:       }/* end jk */ 
                   5921:     }/* end i */ 
1.222     brouard  5922:      /*} *//* end i1 */
1.227     brouard  5923:   } /* end j1 */
1.222     brouard  5924:   
1.227     brouard  5925:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5926:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5927:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5928: }  /* End of prevalence */
1.126     brouard  5929: 
                   5930: /************* Waves Concatenation ***************/
                   5931: 
                   5932: 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)
                   5933: {
1.298     brouard  5934:   /* 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  5935:      Death is a valid wave (if date is known).
                   5936:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5937:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5938:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5939:   */
1.126     brouard  5940: 
1.224     brouard  5941:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5942:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5943:      double sum=0., jmean=0.;*/
1.224     brouard  5944:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5945:   int j, k=0,jk, ju, jl;
                   5946:   double sum=0.;
                   5947:   first=0;
1.214     brouard  5948:   firstwo=0;
1.217     brouard  5949:   firsthree=0;
1.218     brouard  5950:   firstfour=0;
1.164     brouard  5951:   jmin=100000;
1.126     brouard  5952:   jmax=-1;
                   5953:   jmean=0.;
1.224     brouard  5954: 
                   5955: /* Treating live states */
1.214     brouard  5956:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5957:     mi=0;  /* First valid wave */
1.227     brouard  5958:     mli=0; /* Last valid wave */
1.309     brouard  5959:     m=firstpass;  /* Loop on waves */
                   5960:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5961:       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 */
                   5962:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5963:       }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  5964:        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  5965:        mli=m;
1.224     brouard  5966:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5967:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5968:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5969:       }
1.309     brouard  5970:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5971: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5972:        break;
1.224     brouard  5973: #else
1.317     brouard  5974:        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  5975:          if(firsthree == 0){
1.302     brouard  5976:            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  5977:            firsthree=1;
1.317     brouard  5978:          }else if(firsthree >=1 && firsthree < 10){
                   5979:            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);
                   5980:            firsthree++;
                   5981:          }else if(firsthree == 10){
                   5982:            printf("Information, too many Information flags: no more reported to log either\n");
                   5983:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5984:            firsthree++;
                   5985:          }else{
                   5986:            firsthree++;
1.227     brouard  5987:          }
1.309     brouard  5988:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5989:          mli=m;
                   5990:        }
                   5991:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5992:          nbwarn++;
1.309     brouard  5993:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5994:            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);
                   5995:            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);
                   5996:          }
                   5997:          break;
                   5998:        }
                   5999:        break;
1.224     brouard  6000: #endif
1.227     brouard  6001:       }/* End m >= lastpass */
1.126     brouard  6002:     }/* end while */
1.224     brouard  6003: 
1.227     brouard  6004:     /* 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  6005:     /* After last pass */
1.224     brouard  6006: /* Treating death states */
1.214     brouard  6007:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6008:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6009:       /* } */
1.126     brouard  6010:       mi++;    /* Death is another wave */
                   6011:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6012:       /* Only death is a correct wave */
1.126     brouard  6013:       mw[mi][i]=m;
1.257     brouard  6014:     } /* else not in a death state */
1.224     brouard  6015: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6016:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6017:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6018:        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  6019:          nbwarn++;
                   6020:          if(firstfiv==0){
1.309     brouard  6021:            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  6022:            firstfiv=1;
                   6023:          }else{
1.309     brouard  6024:            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  6025:          }
1.309     brouard  6026:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6027:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6028:          nberr++;
                   6029:          if(firstwo==0){
1.309     brouard  6030:            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  6031:            firstwo=1;
                   6032:          }
1.309     brouard  6033:          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  6034:        }
1.257     brouard  6035:       }else{ /* if date of interview is unknown */
1.227     brouard  6036:        /* death is known but not confirmed by death status at any wave */
                   6037:        if(firstfour==0){
1.309     brouard  6038:          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  6039:          firstfour=1;
                   6040:        }
1.309     brouard  6041:        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  6042:       }
1.224     brouard  6043:     } /* end if date of death is known */
                   6044: #endif
1.309     brouard  6045:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6046:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6047:     if(mi==0){
                   6048:       nbwarn++;
                   6049:       if(first==0){
1.227     brouard  6050:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6051:        first=1;
1.126     brouard  6052:       }
                   6053:       if(first==1){
1.227     brouard  6054:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6055:       }
                   6056:     } /* end mi==0 */
                   6057:   } /* End individuals */
1.214     brouard  6058:   /* wav and mw are no more changed */
1.223     brouard  6059:        
1.317     brouard  6060:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6061:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6062: 
                   6063: 
1.126     brouard  6064:   for(i=1; i<=imx; i++){
                   6065:     for(mi=1; mi<wav[i];mi++){
                   6066:       if (stepm <=0)
1.227     brouard  6067:        dh[mi][i]=1;
1.126     brouard  6068:       else{
1.260     brouard  6069:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6070:          if (agedc[i] < 2*AGESUP) {
                   6071:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6072:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6073:            else if(j<0){
                   6074:              nberr++;
                   6075:              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]);
                   6076:              j=1; /* Temporary Dangerous patch */
                   6077:              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);
                   6078:              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]);
                   6079:              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);
                   6080:            }
                   6081:            k=k+1;
                   6082:            if (j >= jmax){
                   6083:              jmax=j;
                   6084:              ijmax=i;
                   6085:            }
                   6086:            if (j <= jmin){
                   6087:              jmin=j;
                   6088:              ijmin=i;
                   6089:            }
                   6090:            sum=sum+j;
                   6091:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6092:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6093:          }
                   6094:        }
                   6095:        else{
                   6096:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6097: /*       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  6098:                                        
1.227     brouard  6099:          k=k+1;
                   6100:          if (j >= jmax) {
                   6101:            jmax=j;
                   6102:            ijmax=i;
                   6103:          }
                   6104:          else if (j <= jmin){
                   6105:            jmin=j;
                   6106:            ijmin=i;
                   6107:          }
                   6108:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6109:          /*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]);*/
                   6110:          if(j<0){
                   6111:            nberr++;
                   6112:            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]);
                   6113:            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]);
                   6114:          }
                   6115:          sum=sum+j;
                   6116:        }
                   6117:        jk= j/stepm;
                   6118:        jl= j -jk*stepm;
                   6119:        ju= j -(jk+1)*stepm;
                   6120:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6121:          if(jl==0){
                   6122:            dh[mi][i]=jk;
                   6123:            bh[mi][i]=0;
                   6124:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6125:                  * to avoid the price of an extra matrix product in likelihood */
                   6126:            dh[mi][i]=jk+1;
                   6127:            bh[mi][i]=ju;
                   6128:          }
                   6129:        }else{
                   6130:          if(jl <= -ju){
                   6131:            dh[mi][i]=jk;
                   6132:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6133:                                 * is higher than the multiple of stepm and negative otherwise.
                   6134:                                 */
                   6135:          }
                   6136:          else{
                   6137:            dh[mi][i]=jk+1;
                   6138:            bh[mi][i]=ju;
                   6139:          }
                   6140:          if(dh[mi][i]==0){
                   6141:            dh[mi][i]=1; /* At least one step */
                   6142:            bh[mi][i]=ju; /* At least one step */
                   6143:            /*  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);*/
                   6144:          }
                   6145:        } /* end if mle */
1.126     brouard  6146:       }
                   6147:     } /* end wave */
                   6148:   }
                   6149:   jmean=sum/k;
                   6150:   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  6151:   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  6152: }
1.126     brouard  6153: 
                   6154: /*********** Tricode ****************************/
1.220     brouard  6155:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6156:  {
                   6157:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6158:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6159:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6160:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6161:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6162:     */
1.130     brouard  6163: 
1.242     brouard  6164:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6165:    int modmaxcovj=0; /* Modality max of covariates j */
                   6166:    int cptcode=0; /* Modality max of covariates j */
                   6167:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6168: 
                   6169: 
1.242     brouard  6170:    /* cptcoveff=0;  */
                   6171:    /* *cptcov=0; */
1.126     brouard  6172:  
1.242     brouard  6173:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6174:    for (k=1; k <= maxncov; k++)
                   6175:      for(j=1; j<=2; j++)
                   6176:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6177: 
1.242     brouard  6178:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6179:    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  6180:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.339     brouard  6181:      printf("Testing k=%d, cptcovt=%d\n",k, cptcovt);
                   6182:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6183:        switch(Fixed[k]) {
                   6184:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6185:         modmaxcovj=0;
                   6186:         modmincovj=0;
1.242     brouard  6187:         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  6188:           /* 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  6189:           ij=(int)(covar[Tvar[k]][i]);
                   6190:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6191:            * If product of Vn*Vm, still boolean *:
                   6192:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6193:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6194:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6195:              modality of the nth covariate of individual i. */
                   6196:           if (ij > modmaxcovj)
                   6197:             modmaxcovj=ij; 
                   6198:           else if (ij < modmincovj) 
                   6199:             modmincovj=ij; 
1.287     brouard  6200:           if (ij <0 || ij >1 ){
1.311     brouard  6201:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6202:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6203:             fflush(ficlog);
                   6204:             exit(1);
1.287     brouard  6205:           }
                   6206:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6207:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6208:             exit(1);
                   6209:           }else
                   6210:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6211:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6212:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6213:           /* getting the maximum value of the modality of the covariate
                   6214:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6215:              female ies 1, then modmaxcovj=1.
                   6216:           */
                   6217:         } /* end for loop on individuals i */
                   6218:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6219:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6220:         cptcode=modmaxcovj;
                   6221:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6222:         /*for (i=0; i<=cptcode; i++) {*/
                   6223:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6224:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6225:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6226:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6227:             if( j != -1){
                   6228:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6229:                                  covariate for which somebody answered excluding 
                   6230:                                  undefined. Usually 2: 0 and 1. */
                   6231:             }
                   6232:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6233:                                     covariate for which somebody answered including 
                   6234:                                     undefined. Usually 3: -1, 0 and 1. */
                   6235:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6236:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6237:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6238:                        
1.242     brouard  6239:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6240:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6241:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6242:         /* modmincovj=3; modmaxcovj = 7; */
                   6243:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6244:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6245:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6246:         /* nbcode[Tvar[j]][ij]=k; */
                   6247:         /* nbcode[Tvar[j]][1]=0; */
                   6248:         /* nbcode[Tvar[j]][2]=1; */
                   6249:         /* nbcode[Tvar[j]][3]=2; */
                   6250:         /* To be continued (not working yet). */
                   6251:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6252: 
                   6253:         /* 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*/
                   6254:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6255:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6256:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6257:         /*, could be restored in the future */
                   6258:         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  6259:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6260:             break;
                   6261:           }
                   6262:           ij++;
1.287     brouard  6263:           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  6264:           cptcode = ij; /* New max modality for covar j */
                   6265:         } /* end of loop on modality i=-1 to 1 or more */
                   6266:         break;
                   6267:        case 1: /* Testing on varying covariate, could be simple and
                   6268:                * should look at waves or product of fixed *
                   6269:                * varying. No time to test -1, assuming 0 and 1 only */
                   6270:         ij=0;
                   6271:         for(i=0; i<=1;i++){
                   6272:           nbcode[Tvar[k]][++ij]=i;
                   6273:         }
                   6274:         break;
                   6275:        default:
                   6276:         break;
                   6277:        } /* end switch */
                   6278:      } /* end dummy test */
1.342   ! brouard  6279:      if(Dummy[k]==1 && Typevar[k] !=1 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6280:        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  6281:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6282:           printf("Error k=%d \n",k);
                   6283:           exit(1);
                   6284:         }
1.311     brouard  6285:         if(isnan(covar[Tvar[k]][i])){
                   6286:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6287:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6288:           fflush(ficlog);
                   6289:           exit(1);
                   6290:          }
                   6291:        }
1.335     brouard  6292:      } /* end Quanti */
1.287     brouard  6293:    } /* 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  6294:   
                   6295:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6296:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6297:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6298:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6299:      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 */ 
                   6300:      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 */
                   6301:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6302:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6303:   
                   6304:    ij=0;
                   6305:    /* 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  6306:    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 */
                   6307:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6308:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6309:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6310:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6311:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6312:        /* 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  6313:        /* If product not in single variable we don't print results */
                   6314:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6315:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6316:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6317:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6318:        /* ij            1    2                                            3  */  
                   6319:        /* Tvaraff[ij]=  4    3                                            1  */
                   6320:        /* Tmodelind[ij]=2    3                                            9  */
                   6321:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6322:        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*/
                   6323:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6324:        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 */
                   6325:        if(Fixed[k]!=0)
                   6326:         anyvaryingduminmodel=1;
                   6327:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6328:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6329:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6330:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6331:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6332:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6333:      } 
                   6334:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6335:    /* ij--; */
                   6336:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6337:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6338:                * because they can be excluded from the model and real
                   6339:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6340:    for(j=ij+1; j<= cptcovt; j++){
                   6341:      Tvaraff[j]=0;
                   6342:      Tmodelind[j]=0;
                   6343:    }
                   6344:    for(j=ntveff+1; j<= cptcovt; j++){
                   6345:      TmodelInvind[j]=0;
                   6346:    }
                   6347:    /* To be sorted */
                   6348:    ;
                   6349:  }
1.126     brouard  6350: 
1.145     brouard  6351: 
1.126     brouard  6352: /*********** Health Expectancies ****************/
                   6353: 
1.235     brouard  6354:  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  6355: 
                   6356: {
                   6357:   /* Health expectancies, no variances */
1.329     brouard  6358:   /* cij is the combination in the list of combination of dummy covariates */
                   6359:   /* strstart is a string of time at start of computing */
1.164     brouard  6360:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6361:   int nhstepma, nstepma; /* Decreasing with age */
                   6362:   double age, agelim, hf;
                   6363:   double ***p3mat;
                   6364:   double eip;
                   6365: 
1.238     brouard  6366:   /* pstamp(ficreseij); */
1.126     brouard  6367:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6368:   fprintf(ficreseij,"# Age");
                   6369:   for(i=1; i<=nlstate;i++){
                   6370:     for(j=1; j<=nlstate;j++){
                   6371:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6372:     }
                   6373:     fprintf(ficreseij," e%1d. ",i);
                   6374:   }
                   6375:   fprintf(ficreseij,"\n");
                   6376: 
                   6377:   
                   6378:   if(estepm < stepm){
                   6379:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6380:   }
                   6381:   else  hstepm=estepm;   
                   6382:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6383:    * This is mainly to measure the difference between two models: for example
                   6384:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6385:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6386:    * progression in between and thus overestimating or underestimating according
                   6387:    * to the curvature of the survival function. If, for the same date, we 
                   6388:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6389:    * to compare the new estimate of Life expectancy with the same linear 
                   6390:    * hypothesis. A more precise result, taking into account a more precise
                   6391:    * curvature will be obtained if estepm is as small as stepm. */
                   6392: 
                   6393:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6394:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6395:      nhstepm is the number of hstepm from age to agelim 
                   6396:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6397:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6398:      and note for a fixed period like estepm months */
                   6399:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6400:      survival function given by stepm (the optimization length). Unfortunately it
                   6401:      means that if the survival funtion is printed only each two years of age and if
                   6402:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6403:      results. So we changed our mind and took the option of the best precision.
                   6404:   */
                   6405:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6406: 
                   6407:   agelim=AGESUP;
                   6408:   /* If stepm=6 months */
                   6409:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6410:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6411:     
                   6412: /* nhstepm age range expressed in number of stepm */
                   6413:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6414:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6415:   /* if (stepm >= YEARM) hstepm=1;*/
                   6416:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6417:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6418: 
                   6419:   for (age=bage; age<=fage; age ++){ 
                   6420:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6421:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6422:     /* if (stepm >= YEARM) hstepm=1;*/
                   6423:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6424: 
                   6425:     /* If stepm=6 months */
                   6426:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6427:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6428:     /* 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  6429:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6430:     
                   6431:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6432:     
                   6433:     printf("%d|",(int)age);fflush(stdout);
                   6434:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6435:     
                   6436:     /* Computing expectancies */
                   6437:     for(i=1; i<=nlstate;i++)
                   6438:       for(j=1; j<=nlstate;j++)
                   6439:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6440:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6441:          
                   6442:          /* 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]);*/
                   6443: 
                   6444:        }
                   6445: 
                   6446:     fprintf(ficreseij,"%3.0f",age );
                   6447:     for(i=1; i<=nlstate;i++){
                   6448:       eip=0;
                   6449:       for(j=1; j<=nlstate;j++){
                   6450:        eip +=eij[i][j][(int)age];
                   6451:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6452:       }
                   6453:       fprintf(ficreseij,"%9.4f", eip );
                   6454:     }
                   6455:     fprintf(ficreseij,"\n");
                   6456:     
                   6457:   }
                   6458:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6459:   printf("\n");
                   6460:   fprintf(ficlog,"\n");
                   6461:   
                   6462: }
                   6463: 
1.235     brouard  6464:  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  6465: 
                   6466: {
                   6467:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6468:      to initial status i, ei. .
1.126     brouard  6469:   */
1.336     brouard  6470:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6471:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6472:   int nhstepma, nstepma; /* Decreasing with age */
                   6473:   double age, agelim, hf;
                   6474:   double ***p3matp, ***p3matm, ***varhe;
                   6475:   double **dnewm,**doldm;
                   6476:   double *xp, *xm;
                   6477:   double **gp, **gm;
                   6478:   double ***gradg, ***trgradg;
                   6479:   int theta;
                   6480: 
                   6481:   double eip, vip;
                   6482: 
                   6483:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6484:   xp=vector(1,npar);
                   6485:   xm=vector(1,npar);
                   6486:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6487:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6488:   
                   6489:   pstamp(ficresstdeij);
                   6490:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6491:   fprintf(ficresstdeij,"# Age");
                   6492:   for(i=1; i<=nlstate;i++){
                   6493:     for(j=1; j<=nlstate;j++)
                   6494:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6495:     fprintf(ficresstdeij," e%1d. ",i);
                   6496:   }
                   6497:   fprintf(ficresstdeij,"\n");
                   6498: 
                   6499:   pstamp(ficrescveij);
                   6500:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6501:   fprintf(ficrescveij,"# Age");
                   6502:   for(i=1; i<=nlstate;i++)
                   6503:     for(j=1; j<=nlstate;j++){
                   6504:       cptj= (j-1)*nlstate+i;
                   6505:       for(i2=1; i2<=nlstate;i2++)
                   6506:        for(j2=1; j2<=nlstate;j2++){
                   6507:          cptj2= (j2-1)*nlstate+i2;
                   6508:          if(cptj2 <= cptj)
                   6509:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6510:        }
                   6511:     }
                   6512:   fprintf(ficrescveij,"\n");
                   6513:   
                   6514:   if(estepm < stepm){
                   6515:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6516:   }
                   6517:   else  hstepm=estepm;   
                   6518:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6519:    * This is mainly to measure the difference between two models: for example
                   6520:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6521:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6522:    * progression in between and thus overestimating or underestimating according
                   6523:    * to the curvature of the survival function. If, for the same date, we 
                   6524:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6525:    * to compare the new estimate of Life expectancy with the same linear 
                   6526:    * hypothesis. A more precise result, taking into account a more precise
                   6527:    * curvature will be obtained if estepm is as small as stepm. */
                   6528: 
                   6529:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6530:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6531:      nhstepm is the number of hstepm from age to agelim 
                   6532:      nstepm is the number of stepm from age to agelin. 
                   6533:      Look at hpijx to understand the reason of that which relies in memory size
                   6534:      and note for a fixed period like estepm months */
                   6535:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6536:      survival function given by stepm (the optimization length). Unfortunately it
                   6537:      means that if the survival funtion is printed only each two years of age and if
                   6538:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6539:      results. So we changed our mind and took the option of the best precision.
                   6540:   */
                   6541:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6542: 
                   6543:   /* If stepm=6 months */
                   6544:   /* nhstepm age range expressed in number of stepm */
                   6545:   agelim=AGESUP;
                   6546:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6547:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6548:   /* if (stepm >= YEARM) hstepm=1;*/
                   6549:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6550:   
                   6551:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6552:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6553:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6554:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6555:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6556:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6557: 
                   6558:   for (age=bage; age<=fage; age ++){ 
                   6559:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6560:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6561:     /* if (stepm >= YEARM) hstepm=1;*/
                   6562:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6563:                
1.126     brouard  6564:     /* If stepm=6 months */
                   6565:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6566:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6567:     
                   6568:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6569:                
1.126     brouard  6570:     /* Computing  Variances of health expectancies */
                   6571:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6572:        decrease memory allocation */
                   6573:     for(theta=1; theta <=npar; theta++){
                   6574:       for(i=1; i<=npar; i++){ 
1.222     brouard  6575:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6576:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6577:       }
1.235     brouard  6578:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6579:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6580:                        
1.126     brouard  6581:       for(j=1; j<= nlstate; j++){
1.222     brouard  6582:        for(i=1; i<=nlstate; i++){
                   6583:          for(h=0; h<=nhstepm-1; h++){
                   6584:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6585:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6586:          }
                   6587:        }
1.126     brouard  6588:       }
1.218     brouard  6589:                        
1.126     brouard  6590:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6591:        for(h=0; h<=nhstepm-1; h++){
                   6592:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6593:        }
1.126     brouard  6594:     }/* End theta */
                   6595:     
                   6596:     
                   6597:     for(h=0; h<=nhstepm-1; h++)
                   6598:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6599:        for(theta=1; theta <=npar; theta++)
                   6600:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6601:     
1.218     brouard  6602:                
1.222     brouard  6603:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6604:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6605:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6606:                
1.222     brouard  6607:     printf("%d|",(int)age);fflush(stdout);
                   6608:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6609:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6610:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6611:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6612:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6613:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6614:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6615:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6616:       }
                   6617:     }
1.320     brouard  6618:     /* if((int)age ==50){ */
                   6619:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6620:     /* } */
1.126     brouard  6621:     /* Computing expectancies */
1.235     brouard  6622:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6623:     for(i=1; i<=nlstate;i++)
                   6624:       for(j=1; j<=nlstate;j++)
1.222     brouard  6625:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6626:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6627:                                        
1.222     brouard  6628:          /* 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  6629:                                        
1.222     brouard  6630:        }
1.269     brouard  6631: 
                   6632:     /* Standard deviation of expectancies ij */                
1.126     brouard  6633:     fprintf(ficresstdeij,"%3.0f",age );
                   6634:     for(i=1; i<=nlstate;i++){
                   6635:       eip=0.;
                   6636:       vip=0.;
                   6637:       for(j=1; j<=nlstate;j++){
1.222     brouard  6638:        eip += eij[i][j][(int)age];
                   6639:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6640:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6641:        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  6642:       }
                   6643:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6644:     }
                   6645:     fprintf(ficresstdeij,"\n");
1.218     brouard  6646:                
1.269     brouard  6647:     /* Variance of expectancies ij */          
1.126     brouard  6648:     fprintf(ficrescveij,"%3.0f",age );
                   6649:     for(i=1; i<=nlstate;i++)
                   6650:       for(j=1; j<=nlstate;j++){
1.222     brouard  6651:        cptj= (j-1)*nlstate+i;
                   6652:        for(i2=1; i2<=nlstate;i2++)
                   6653:          for(j2=1; j2<=nlstate;j2++){
                   6654:            cptj2= (j2-1)*nlstate+i2;
                   6655:            if(cptj2 <= cptj)
                   6656:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6657:          }
1.126     brouard  6658:       }
                   6659:     fprintf(ficrescveij,"\n");
1.218     brouard  6660:                
1.126     brouard  6661:   }
                   6662:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6663:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6664:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6665:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6666:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6667:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6668:   printf("\n");
                   6669:   fprintf(ficlog,"\n");
1.218     brouard  6670:        
1.126     brouard  6671:   free_vector(xm,1,npar);
                   6672:   free_vector(xp,1,npar);
                   6673:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6674:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6675:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6676: }
1.218     brouard  6677:  
1.126     brouard  6678: /************ Variance ******************/
1.235     brouard  6679:  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  6680:  {
1.279     brouard  6681:    /** Variance of health expectancies 
                   6682:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6683:     * double **newm;
                   6684:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6685:     */
1.218     brouard  6686:   
                   6687:    /* int movingaverage(); */
                   6688:    double **dnewm,**doldm;
                   6689:    double **dnewmp,**doldmp;
                   6690:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6691:    int first=0;
1.218     brouard  6692:    int k;
                   6693:    double *xp;
1.279     brouard  6694:    double **gp, **gm;  /**< for var eij */
                   6695:    double ***gradg, ***trgradg; /**< for var eij */
                   6696:    double **gradgp, **trgradgp; /**< for var p point j */
                   6697:    double *gpp, *gmp; /**< for var p point j */
                   6698:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6699:    double ***p3mat;
                   6700:    double age,agelim, hf;
                   6701:    /* double ***mobaverage; */
                   6702:    int theta;
                   6703:    char digit[4];
                   6704:    char digitp[25];
                   6705: 
                   6706:    char fileresprobmorprev[FILENAMELENGTH];
                   6707: 
                   6708:    if(popbased==1){
                   6709:      if(mobilav!=0)
                   6710:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6711:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6712:    }
                   6713:    else 
                   6714:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6715: 
1.218     brouard  6716:    /* if (mobilav!=0) { */
                   6717:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6718:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6719:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6720:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6721:    /*   } */
                   6722:    /* } */
                   6723: 
                   6724:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6725:    sprintf(digit,"%-d",ij);
                   6726:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6727:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6728:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6729:    strcat(fileresprobmorprev,fileresu);
                   6730:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6731:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6732:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6733:    }
                   6734:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6735:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6736:    pstamp(ficresprobmorprev);
                   6737:    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  6738:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6739: 
                   6740:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6741:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6742:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6743:    /* } */
                   6744:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
                   6745:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6746:    }
1.337     brouard  6747:    /* for(j=1;j<=cptcoveff;j++)  */
                   6748:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6749:    fprintf(ficresprobmorprev,"\n");
                   6750: 
1.218     brouard  6751:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6752:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6753:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6754:      for(i=1; i<=nlstate;i++)
                   6755:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6756:    }  
                   6757:    fprintf(ficresprobmorprev,"\n");
                   6758:   
                   6759:    fprintf(ficgp,"\n# Routine varevsij");
                   6760:    fprintf(ficgp,"\nunset title \n");
                   6761:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6762:    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");
                   6763:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6764: 
1.218     brouard  6765:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6766:    pstamp(ficresvij);
                   6767:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6768:    if(popbased==1)
                   6769:      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);
                   6770:    else
                   6771:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6772:    fprintf(ficresvij,"# Age");
                   6773:    for(i=1; i<=nlstate;i++)
                   6774:      for(j=1; j<=nlstate;j++)
                   6775:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6776:    fprintf(ficresvij,"\n");
                   6777: 
                   6778:    xp=vector(1,npar);
                   6779:    dnewm=matrix(1,nlstate,1,npar);
                   6780:    doldm=matrix(1,nlstate,1,nlstate);
                   6781:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6782:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6783: 
                   6784:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6785:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6786:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6787:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6788:   
1.218     brouard  6789:    if(estepm < stepm){
                   6790:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6791:    }
                   6792:    else  hstepm=estepm;   
                   6793:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6794:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6795:       nhstepm is the number of hstepm from age to agelim 
                   6796:       nstepm is the number of stepm from age to agelim. 
                   6797:       Look at function hpijx to understand why because of memory size limitations, 
                   6798:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6799:       survival function given by stepm (the optimization length). Unfortunately it
                   6800:       means that if the survival funtion is printed every two years of age and if
                   6801:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6802:       results. So we changed our mind and took the option of the best precision.
                   6803:    */
                   6804:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6805:    agelim = AGESUP;
                   6806:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6807:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6808:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6809:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6810:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6811:      gp=matrix(0,nhstepm,1,nlstate);
                   6812:      gm=matrix(0,nhstepm,1,nlstate);
                   6813:                
                   6814:                
                   6815:      for(theta=1; theta <=npar; theta++){
                   6816:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6817:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6818:        }
1.279     brouard  6819:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6820:        * returns into prlim .
1.288     brouard  6821:        */
1.242     brouard  6822:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6823: 
                   6824:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6825:        if (popbased==1) {
                   6826:         if(mobilav ==0){
                   6827:           for(i=1; i<=nlstate;i++)
                   6828:             prlim[i][i]=probs[(int)age][i][ij];
                   6829:         }else{ /* mobilav */ 
                   6830:           for(i=1; i<=nlstate;i++)
                   6831:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6832:         }
                   6833:        }
1.295     brouard  6834:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6835:        */                      
                   6836:        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  6837:        /**< 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  6838:        * at horizon h in state j including mortality.
                   6839:        */
1.218     brouard  6840:        for(j=1; j<= nlstate; j++){
                   6841:         for(h=0; h<=nhstepm; h++){
                   6842:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6843:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6844:         }
                   6845:        }
1.279     brouard  6846:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6847:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6848:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6849:        */
                   6850:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6851:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6852:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6853:        }
                   6854:        
                   6855:        /* Again with minus shift */
1.218     brouard  6856:                        
                   6857:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6858:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6859: 
1.242     brouard  6860:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6861:                        
                   6862:        if (popbased==1) {
                   6863:         if(mobilav ==0){
                   6864:           for(i=1; i<=nlstate;i++)
                   6865:             prlim[i][i]=probs[(int)age][i][ij];
                   6866:         }else{ /* mobilav */ 
                   6867:           for(i=1; i<=nlstate;i++)
                   6868:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6869:         }
                   6870:        }
                   6871:                        
1.235     brouard  6872:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6873:                        
                   6874:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6875:         for(h=0; h<=nhstepm; h++){
                   6876:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6877:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6878:         }
                   6879:        }
                   6880:        /* This for computing probability of death (h=1 means
                   6881:          computed over hstepm matrices product = hstepm*stepm months) 
                   6882:          as a weighted average of prlim.
                   6883:        */
                   6884:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6885:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6886:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6887:        }    
1.279     brouard  6888:        /* end shifting computations */
                   6889: 
                   6890:        /**< Computing gradient matrix at horizon h 
                   6891:        */
1.218     brouard  6892:        for(j=1; j<= nlstate; j++) /* vareij */
                   6893:         for(h=0; h<=nhstepm; h++){
                   6894:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6895:         }
1.279     brouard  6896:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6897:        */
                   6898:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6899:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6900:        }
                   6901:                        
                   6902:      } /* End theta */
1.279     brouard  6903:      
                   6904:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6905:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6906:                
                   6907:      for(h=0; h<=nhstepm; h++) /* veij */
                   6908:        for(j=1; j<=nlstate;j++)
                   6909:         for(theta=1; theta <=npar; theta++)
                   6910:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6911:                
                   6912:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6913:        for(theta=1; theta <=npar; theta++)
                   6914:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6915:      /**< as well as its transposed matrix 
                   6916:       */               
1.218     brouard  6917:                
                   6918:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6919:      for(i=1;i<=nlstate;i++)
                   6920:        for(j=1;j<=nlstate;j++)
                   6921:         vareij[i][j][(int)age] =0.;
1.279     brouard  6922: 
                   6923:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6924:       * and k (nhstepm) formula 15 of article
                   6925:       * Lievre-Brouard-Heathcote
                   6926:       */
                   6927:      
1.218     brouard  6928:      for(h=0;h<=nhstepm;h++){
                   6929:        for(k=0;k<=nhstepm;k++){
                   6930:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6931:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6932:         for(i=1;i<=nlstate;i++)
                   6933:           for(j=1;j<=nlstate;j++)
                   6934:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6935:        }
                   6936:      }
                   6937:                
1.279     brouard  6938:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6939:       * p.j overall mortality formula 49 but computed directly because
                   6940:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6941:       * wix is independent of theta.
                   6942:       */
1.218     brouard  6943:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6944:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6945:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6946:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6947:         varppt[j][i]=doldmp[j][i];
                   6948:      /* end ppptj */
                   6949:      /*  x centered again */
                   6950:                
1.242     brouard  6951:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6952:                
                   6953:      if (popbased==1) {
                   6954:        if(mobilav ==0){
                   6955:         for(i=1; i<=nlstate;i++)
                   6956:           prlim[i][i]=probs[(int)age][i][ij];
                   6957:        }else{ /* mobilav */ 
                   6958:         for(i=1; i<=nlstate;i++)
                   6959:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6960:        }
                   6961:      }
                   6962:                
                   6963:      /* This for computing probability of death (h=1 means
                   6964:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6965:        as a weighted average of prlim.
                   6966:      */
1.235     brouard  6967:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6968:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6969:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6970:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6971:      }    
                   6972:      /* end probability of death */
                   6973:                
                   6974:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6975:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6976:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6977:        for(i=1; i<=nlstate;i++){
                   6978:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6979:        }
                   6980:      } 
                   6981:      fprintf(ficresprobmorprev,"\n");
                   6982:                
                   6983:      fprintf(ficresvij,"%.0f ",age );
                   6984:      for(i=1; i<=nlstate;i++)
                   6985:        for(j=1; j<=nlstate;j++){
                   6986:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6987:        }
                   6988:      fprintf(ficresvij,"\n");
                   6989:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6990:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6991:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6992:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6993:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6994:    } /* End age */
                   6995:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6996:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6997:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6998:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6999:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7000:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7001:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7002:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7003:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7004:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7005:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7006:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7007:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7008:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7009:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7010:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7011:    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);
                   7012:    /*  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  7013:     */
1.218     brouard  7014:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7015:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7016: 
1.218     brouard  7017:    free_vector(xp,1,npar);
                   7018:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7019:    free_matrix(dnewm,1,nlstate,1,npar);
                   7020:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7021:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7022:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7023:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7024:    fclose(ficresprobmorprev);
                   7025:    fflush(ficgp);
                   7026:    fflush(fichtm); 
                   7027:  }  /* end varevsij */
1.126     brouard  7028: 
                   7029: /************ Variance of prevlim ******************/
1.269     brouard  7030:  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  7031: {
1.205     brouard  7032:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7033:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7034: 
1.268     brouard  7035:   double **dnewmpar,**doldm;
1.126     brouard  7036:   int i, j, nhstepm, hstepm;
                   7037:   double *xp;
                   7038:   double *gp, *gm;
                   7039:   double **gradg, **trgradg;
1.208     brouard  7040:   double **mgm, **mgp;
1.126     brouard  7041:   double age,agelim;
                   7042:   int theta;
                   7043:   
                   7044:   pstamp(ficresvpl);
1.288     brouard  7045:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7046:   fprintf(ficresvpl,"# Age ");
                   7047:   if(nresult >=1)
                   7048:     fprintf(ficresvpl," Result# ");
1.126     brouard  7049:   for(i=1; i<=nlstate;i++)
                   7050:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7051:   fprintf(ficresvpl,"\n");
                   7052: 
                   7053:   xp=vector(1,npar);
1.268     brouard  7054:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7055:   doldm=matrix(1,nlstate,1,nlstate);
                   7056:   
                   7057:   hstepm=1*YEARM; /* Every year of age */
                   7058:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7059:   agelim = AGESUP;
                   7060:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7061:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7062:     if (stepm >= YEARM) hstepm=1;
                   7063:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7064:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7065:     mgp=matrix(1,npar,1,nlstate);
                   7066:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7067:     gp=vector(1,nlstate);
                   7068:     gm=vector(1,nlstate);
                   7069: 
                   7070:     for(theta=1; theta <=npar; theta++){
                   7071:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7072:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7073:       }
1.288     brouard  7074:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7075:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7076:       /* else */
                   7077:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7078:       for(i=1;i<=nlstate;i++){
1.126     brouard  7079:        gp[i] = prlim[i][i];
1.208     brouard  7080:        mgp[theta][i] = prlim[i][i];
                   7081:       }
1.126     brouard  7082:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7083:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7084:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7085:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7086:       /* else */
                   7087:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7088:       for(i=1;i<=nlstate;i++){
1.126     brouard  7089:        gm[i] = prlim[i][i];
1.208     brouard  7090:        mgm[theta][i] = prlim[i][i];
                   7091:       }
1.126     brouard  7092:       for(i=1;i<=nlstate;i++)
                   7093:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7094:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7095:     } /* End theta */
                   7096: 
                   7097:     trgradg =matrix(1,nlstate,1,npar);
                   7098: 
                   7099:     for(j=1; j<=nlstate;j++)
                   7100:       for(theta=1; theta <=npar; theta++)
                   7101:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7102:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7103:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7104:     /*   for(j=1; j<=nlstate;j++){ */
                   7105:     /*         printf(" %d ",j); */
                   7106:     /*         for(theta=1; theta <=npar; theta++) */
                   7107:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7108:     /*         printf("\n "); */
                   7109:     /*   } */
                   7110:     /* } */
                   7111:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7112:     /*   printf("\n gradg %d ",(int)age); */
                   7113:     /*   for(j=1; j<=nlstate;j++){ */
                   7114:     /*         printf("%d ",j); */
                   7115:     /*         for(theta=1; theta <=npar; theta++) */
                   7116:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7117:     /*         printf("\n "); */
                   7118:     /*   } */
                   7119:     /* } */
1.126     brouard  7120: 
                   7121:     for(i=1;i<=nlstate;i++)
                   7122:       varpl[i][(int)age] =0.;
1.209     brouard  7123:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7124:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7125:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7126:     }else{
1.268     brouard  7127:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7128:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7129:     }
1.126     brouard  7130:     for(i=1;i<=nlstate;i++)
                   7131:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7132: 
                   7133:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7134:     if(nresult >=1)
                   7135:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7136:     for(i=1; i<=nlstate;i++){
1.126     brouard  7137:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7138:       /* for(j=1;j<=nlstate;j++) */
                   7139:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7140:     }
1.126     brouard  7141:     fprintf(ficresvpl,"\n");
                   7142:     free_vector(gp,1,nlstate);
                   7143:     free_vector(gm,1,nlstate);
1.208     brouard  7144:     free_matrix(mgm,1,npar,1,nlstate);
                   7145:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7146:     free_matrix(gradg,1,npar,1,nlstate);
                   7147:     free_matrix(trgradg,1,nlstate,1,npar);
                   7148:   } /* End age */
                   7149: 
                   7150:   free_vector(xp,1,npar);
                   7151:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7152:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7153: 
                   7154: }
                   7155: 
                   7156: 
                   7157: /************ Variance of backprevalence limit ******************/
1.269     brouard  7158:  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  7159: {
                   7160:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7161:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7162: 
                   7163:   double **dnewmpar,**doldm;
                   7164:   int i, j, nhstepm, hstepm;
                   7165:   double *xp;
                   7166:   double *gp, *gm;
                   7167:   double **gradg, **trgradg;
                   7168:   double **mgm, **mgp;
                   7169:   double age,agelim;
                   7170:   int theta;
                   7171:   
                   7172:   pstamp(ficresvbl);
                   7173:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7174:   fprintf(ficresvbl,"# Age ");
                   7175:   if(nresult >=1)
                   7176:     fprintf(ficresvbl," Result# ");
                   7177:   for(i=1; i<=nlstate;i++)
                   7178:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7179:   fprintf(ficresvbl,"\n");
                   7180: 
                   7181:   xp=vector(1,npar);
                   7182:   dnewmpar=matrix(1,nlstate,1,npar);
                   7183:   doldm=matrix(1,nlstate,1,nlstate);
                   7184:   
                   7185:   hstepm=1*YEARM; /* Every year of age */
                   7186:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7187:   agelim = AGEINF;
                   7188:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7189:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7190:     if (stepm >= YEARM) hstepm=1;
                   7191:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7192:     gradg=matrix(1,npar,1,nlstate);
                   7193:     mgp=matrix(1,npar,1,nlstate);
                   7194:     mgm=matrix(1,npar,1,nlstate);
                   7195:     gp=vector(1,nlstate);
                   7196:     gm=vector(1,nlstate);
                   7197: 
                   7198:     for(theta=1; theta <=npar; theta++){
                   7199:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7200:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7201:       }
                   7202:       if(mobilavproj > 0 )
                   7203:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7204:       else
                   7205:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7206:       for(i=1;i<=nlstate;i++){
                   7207:        gp[i] = bprlim[i][i];
                   7208:        mgp[theta][i] = bprlim[i][i];
                   7209:       }
                   7210:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7211:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7212:        if(mobilavproj > 0 )
                   7213:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7214:        else
                   7215:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7216:       for(i=1;i<=nlstate;i++){
                   7217:        gm[i] = bprlim[i][i];
                   7218:        mgm[theta][i] = bprlim[i][i];
                   7219:       }
                   7220:       for(i=1;i<=nlstate;i++)
                   7221:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7222:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7223:     } /* End theta */
                   7224: 
                   7225:     trgradg =matrix(1,nlstate,1,npar);
                   7226: 
                   7227:     for(j=1; j<=nlstate;j++)
                   7228:       for(theta=1; theta <=npar; theta++)
                   7229:        trgradg[j][theta]=gradg[theta][j];
                   7230:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7231:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7232:     /*   for(j=1; j<=nlstate;j++){ */
                   7233:     /*         printf(" %d ",j); */
                   7234:     /*         for(theta=1; theta <=npar; theta++) */
                   7235:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7236:     /*         printf("\n "); */
                   7237:     /*   } */
                   7238:     /* } */
                   7239:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7240:     /*   printf("\n gradg %d ",(int)age); */
                   7241:     /*   for(j=1; j<=nlstate;j++){ */
                   7242:     /*         printf("%d ",j); */
                   7243:     /*         for(theta=1; theta <=npar; theta++) */
                   7244:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7245:     /*         printf("\n "); */
                   7246:     /*   } */
                   7247:     /* } */
                   7248: 
                   7249:     for(i=1;i<=nlstate;i++)
                   7250:       varbpl[i][(int)age] =0.;
                   7251:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7252:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7253:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7254:     }else{
                   7255:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7256:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7257:     }
                   7258:     for(i=1;i<=nlstate;i++)
                   7259:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7260: 
                   7261:     fprintf(ficresvbl,"%.0f ",age );
                   7262:     if(nresult >=1)
                   7263:       fprintf(ficresvbl,"%d ",nres );
                   7264:     for(i=1; i<=nlstate;i++)
                   7265:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7266:     fprintf(ficresvbl,"\n");
                   7267:     free_vector(gp,1,nlstate);
                   7268:     free_vector(gm,1,nlstate);
                   7269:     free_matrix(mgm,1,npar,1,nlstate);
                   7270:     free_matrix(mgp,1,npar,1,nlstate);
                   7271:     free_matrix(gradg,1,npar,1,nlstate);
                   7272:     free_matrix(trgradg,1,nlstate,1,npar);
                   7273:   } /* End age */
                   7274: 
                   7275:   free_vector(xp,1,npar);
                   7276:   free_matrix(doldm,1,nlstate,1,npar);
                   7277:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7278: 
                   7279: }
                   7280: 
                   7281: /************ Variance of one-step probabilities  ******************/
                   7282: 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  7283:  {
                   7284:    int i, j=0,  k1, l1, tj;
                   7285:    int k2, l2, j1,  z1;
                   7286:    int k=0, l;
                   7287:    int first=1, first1, first2;
1.326     brouard  7288:    int nres=0; /* New */
1.222     brouard  7289:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7290:    double **dnewm,**doldm;
                   7291:    double *xp;
                   7292:    double *gp, *gm;
                   7293:    double **gradg, **trgradg;
                   7294:    double **mu;
                   7295:    double age, cov[NCOVMAX+1];
                   7296:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7297:    int theta;
                   7298:    char fileresprob[FILENAMELENGTH];
                   7299:    char fileresprobcov[FILENAMELENGTH];
                   7300:    char fileresprobcor[FILENAMELENGTH];
                   7301:    double ***varpij;
                   7302: 
                   7303:    strcpy(fileresprob,"PROB_"); 
                   7304:    strcat(fileresprob,fileres);
                   7305:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7306:      printf("Problem with resultfile: %s\n", fileresprob);
                   7307:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7308:    }
                   7309:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7310:    strcat(fileresprobcov,fileresu);
                   7311:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7312:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7313:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7314:    }
                   7315:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7316:    strcat(fileresprobcor,fileresu);
                   7317:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7318:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7319:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7320:    }
                   7321:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7322:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7323:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7324:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7325:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7326:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7327:    pstamp(ficresprob);
                   7328:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7329:    fprintf(ficresprob,"# Age");
                   7330:    pstamp(ficresprobcov);
                   7331:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7332:    fprintf(ficresprobcov,"# Age");
                   7333:    pstamp(ficresprobcor);
                   7334:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7335:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7336: 
                   7337: 
1.222     brouard  7338:    for(i=1; i<=nlstate;i++)
                   7339:      for(j=1; j<=(nlstate+ndeath);j++){
                   7340:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7341:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7342:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7343:      }  
                   7344:    /* fprintf(ficresprob,"\n");
                   7345:       fprintf(ficresprobcov,"\n");
                   7346:       fprintf(ficresprobcor,"\n");
                   7347:    */
                   7348:    xp=vector(1,npar);
                   7349:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7350:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7351:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7352:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7353:    first=1;
                   7354:    fprintf(ficgp,"\n# Routine varprob");
                   7355:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7356:    fprintf(fichtm,"\n");
                   7357: 
1.288     brouard  7358:    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  7359:    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);
                   7360:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7361: and drawn. It helps understanding how is the covariance between two incidences.\
                   7362:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7363:    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  7364: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7365: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7366: standard deviations wide on each axis. <br>\
                   7367:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7368:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7369: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7370: 
1.222     brouard  7371:    cov[1]=1;
                   7372:    /* tj=cptcoveff; */
1.225     brouard  7373:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7374:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7375:    j1=0;
1.332     brouard  7376: 
                   7377:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7378:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342   ! brouard  7379:      /* 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  7380:      if(tj != 1 && TKresult[nres]!= j1)
                   7381:        continue;
                   7382: 
                   7383:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7384:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7385:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7386:      if  (cptcovn>0) {
1.334     brouard  7387:        fprintf(ficresprob, "\n#********** Variable ");
                   7388:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7389:        fprintf(ficgp, "\n#********** Variable ");
                   7390:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7391:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7392: 
                   7393:        /* Including quantitative variables of the resultline to be done */
                   7394:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.338     brouard  7395:         printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7396:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7397:         /* 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  7398:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7399:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7400:             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  */
                   7401:             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  */
                   7402:             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  */
                   7403:             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  */
                   7404:             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  */
                   7405:             fprintf(ficresprob,"fixed ");
                   7406:             fprintf(ficresprobcov,"fixed ");
                   7407:             fprintf(ficgp,"fixed ");
                   7408:             fprintf(fichtmcov,"fixed ");
                   7409:             fprintf(ficresprobcor,"fixed ");
                   7410:           }else{
                   7411:             fprintf(ficresprob,"varyi ");
                   7412:             fprintf(ficresprobcov,"varyi ");
                   7413:             fprintf(ficgp,"varyi ");
                   7414:             fprintf(fichtmcov,"varyi ");
                   7415:             fprintf(ficresprobcor,"varyi ");
                   7416:           }
                   7417:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7418:           /* For each selected (single) quantitative value */
1.337     brouard  7419:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7420:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7421:             fprintf(ficresprob,"fixed ");
                   7422:             fprintf(ficresprobcov,"fixed ");
                   7423:             fprintf(ficgp,"fixed ");
                   7424:             fprintf(fichtmcov,"fixed ");
                   7425:             fprintf(ficresprobcor,"fixed ");
                   7426:           }else{
                   7427:             fprintf(ficresprob,"varyi ");
                   7428:             fprintf(ficresprobcov,"varyi ");
                   7429:             fprintf(ficgp,"varyi ");
                   7430:             fprintf(fichtmcov,"varyi ");
                   7431:             fprintf(ficresprobcor,"varyi ");
                   7432:           }
                   7433:         }else{
                   7434:           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 */
                   7435:           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 */
                   7436:           exit(1);
                   7437:         }
                   7438:        } /* End loop on variable of this resultline */
                   7439:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7440:        fprintf(ficresprob, "**********\n#\n");
                   7441:        fprintf(ficresprobcov, "**********\n#\n");
                   7442:        fprintf(ficgp, "**********\n#\n");
                   7443:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7444:        fprintf(ficresprobcor, "**********\n#");    
                   7445:        if(invalidvarcomb[j1]){
                   7446:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7447:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7448:         continue;
                   7449:        }
                   7450:      }
                   7451:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7452:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7453:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7454:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7455:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7456:        cov[2]=age;
                   7457:        if(nagesqr==1)
                   7458:         cov[3]= age*age;
1.334     brouard  7459:        /* New code end of combination but for each resultline */
                   7460:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7461:         if(Typevar[k1]==1){ /* A product with age */
                   7462:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7463:         }else{
1.334     brouard  7464:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7465:         }
1.334     brouard  7466:        }/* End of loop on model equation */
                   7467: /* Old code */
                   7468:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7469:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7470:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7471:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7472:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7473:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7474:        /*                                                                  * 1  1 1 1 1 */
                   7475:        /*                                                                  * 2  2 1 1 1 */
                   7476:        /*                                                                  * 3  1 2 1 1 */
                   7477:        /*                                                                  *\/ */
                   7478:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7479:        /* } */
                   7480:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7481:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7482:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7483:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7484:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7485:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7486:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7487:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7488:        /*         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]); */
                   7489:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7490:        /*         /\* exit(1); *\/ */
                   7491:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7492:        /*       } */
                   7493:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7494:        /* } */
                   7495:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7496:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7497:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7498:        /*           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]])]; */
                   7499:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7500:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7501:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7502:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7503:        /*         } */
                   7504:        /*       }else{ */
                   7505:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7506:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7507:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7508:        /*         }else{ */
                   7509:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7510:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7511:        /*         } */
                   7512:        /*       } */
                   7513:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7514:        /* } */                 
1.326     brouard  7515: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7516:        for(theta=1; theta <=npar; theta++){
                   7517:         for(i=1; i<=npar; i++)
                   7518:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7519:                                
1.222     brouard  7520:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7521:                                
1.222     brouard  7522:         k=0;
                   7523:         for(i=1; i<= (nlstate); i++){
                   7524:           for(j=1; j<=(nlstate+ndeath);j++){
                   7525:             k=k+1;
                   7526:             gp[k]=pmmij[i][j];
                   7527:           }
                   7528:         }
1.220     brouard  7529:                                
1.222     brouard  7530:         for(i=1; i<=npar; i++)
                   7531:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7532:                                
1.222     brouard  7533:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7534:         k=0;
                   7535:         for(i=1; i<=(nlstate); i++){
                   7536:           for(j=1; j<=(nlstate+ndeath);j++){
                   7537:             k=k+1;
                   7538:             gm[k]=pmmij[i][j];
                   7539:           }
                   7540:         }
1.220     brouard  7541:                                
1.222     brouard  7542:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7543:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7544:        }
1.126     brouard  7545: 
1.222     brouard  7546:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7547:         for(theta=1; theta <=npar; theta++)
                   7548:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7549:                        
1.222     brouard  7550:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7551:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7552:                        
1.222     brouard  7553:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7554:                        
1.222     brouard  7555:        k=0;
                   7556:        for(i=1; i<=(nlstate); i++){
                   7557:         for(j=1; j<=(nlstate+ndeath);j++){
                   7558:           k=k+1;
                   7559:           mu[k][(int) age]=pmmij[i][j];
                   7560:         }
                   7561:        }
                   7562:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7563:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7564:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7565:                        
1.222     brouard  7566:        /*printf("\n%d ",(int)age);
                   7567:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7568:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7569:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7570:         }*/
1.220     brouard  7571:                        
1.222     brouard  7572:        fprintf(ficresprob,"\n%d ",(int)age);
                   7573:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7574:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7575:                        
1.222     brouard  7576:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7577:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7578:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7579:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7580:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7581:        }
                   7582:        i=0;
                   7583:        for (k=1; k<=(nlstate);k++){
                   7584:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7585:           i++;
                   7586:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7587:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7588:           for (j=1; j<=i;j++){
                   7589:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7590:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7591:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7592:           }
                   7593:         }
                   7594:        }/* end of loop for state */
                   7595:      } /* end of loop for age */
                   7596:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7597:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7598:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7599:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7600:     
                   7601:      /* Confidence intervalle of pij  */
                   7602:      /*
                   7603:        fprintf(ficgp,"\nunset parametric;unset label");
                   7604:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7605:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7606:        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);
                   7607:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7608:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7609:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7610:      */
                   7611:                
                   7612:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7613:      first1=1;first2=2;
                   7614:      for (k2=1; k2<=(nlstate);k2++){
                   7615:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7616:         if(l2==k2) continue;
                   7617:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7618:         for (k1=1; k1<=(nlstate);k1++){
                   7619:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7620:             if(l1==k1) continue;
                   7621:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7622:             if(i<=j) continue;
                   7623:             for (age=bage; age<=fage; age ++){ 
                   7624:               if ((int)age %5==0){
                   7625:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7626:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7627:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7628:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7629:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7630:                 c12=cv12/sqrt(v1*v2);
                   7631:                 /* Computing eigen value of matrix of covariance */
                   7632:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7633:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7634:                 if ((lc2 <0) || (lc1 <0) ){
                   7635:                   if(first2==1){
                   7636:                     first1=0;
                   7637:                     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);
                   7638:                   }
                   7639:                   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);
                   7640:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7641:                   /* lc2=fabs(lc2); */
                   7642:                 }
1.220     brouard  7643:                                                                
1.222     brouard  7644:                 /* Eigen vectors */
1.280     brouard  7645:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7646:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7647:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7648:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7649:                 }else
                   7650:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7651:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7652:                 v21=(lc1-v1)/cv12*v11;
                   7653:                 v12=-v21;
                   7654:                 v22=v11;
                   7655:                 tnalp=v21/v11;
                   7656:                 if(first1==1){
                   7657:                   first1=0;
                   7658:                   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);
                   7659:                 }
                   7660:                 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);
                   7661:                 /*printf(fignu*/
                   7662:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7663:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7664:                 if(first==1){
                   7665:                   first=0;
                   7666:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7667:                   fprintf(ficgp,"\nset parametric;unset label");
                   7668:                   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);
                   7669:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7670:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7671:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7672: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7673:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7674:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7675:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7676:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7677:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7678:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7679:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7680:                   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  7681:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7682:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7683:                 }else{
                   7684:                   first=0;
                   7685:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7686:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7687:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7688:                   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  7689:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7690:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7691:                 }/* if first */
                   7692:               } /* age mod 5 */
                   7693:             } /* end loop age */
                   7694:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7695:             first=1;
                   7696:           } /*l12 */
                   7697:         } /* k12 */
                   7698:        } /*l1 */
                   7699:      }/* k1 */
1.332     brouard  7700:    }  /* loop on combination of covariates j1 */
1.326     brouard  7701:    } /* loop on nres */
1.222     brouard  7702:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7703:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7704:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7705:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7706:    free_vector(xp,1,npar);
                   7707:    fclose(ficresprob);
                   7708:    fclose(ficresprobcov);
                   7709:    fclose(ficresprobcor);
                   7710:    fflush(ficgp);
                   7711:    fflush(fichtmcov);
                   7712:  }
1.126     brouard  7713: 
                   7714: 
                   7715: /******************* Printing html file ***********/
1.201     brouard  7716: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7717:                  int lastpass, int stepm, int weightopt, char model[],\
                   7718:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7719:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7720:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7721:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7722:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7723:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7724:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7725:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7726: </ul>");
1.319     brouard  7727: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7728: /* </ul>", model); */
1.214     brouard  7729:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7730:    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",
                   7731:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7732:    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  7733:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7734:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7735:    fprintf(fichtm,"\
                   7736:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7737:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7738:    fprintf(fichtm,"\
1.217     brouard  7739:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7740:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7741:    fprintf(fichtm,"\
1.288     brouard  7742:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7743:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7744:    fprintf(fichtm,"\
1.288     brouard  7745:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7746:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7747:    fprintf(fichtm,"\
1.211     brouard  7748:  - (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  7749:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7750:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7751:    if(prevfcast==1){
                   7752:      fprintf(fichtm,"\
                   7753:  - Prevalence projections by age and states:                           \
1.201     brouard  7754:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7755:    }
1.126     brouard  7756: 
                   7757: 
1.225     brouard  7758:    m=pow(2,cptcoveff);
1.222     brouard  7759:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7760: 
1.317     brouard  7761:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7762: 
                   7763:    jj1=0;
                   7764: 
                   7765:    fprintf(fichtm," \n<ul>");
1.337     brouard  7766:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7767:      /* k1=nres; */
1.338     brouard  7768:      k1=TKresult[nres];
                   7769:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7770:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7771:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7772:    /*     continue; */
1.264     brouard  7773:      jj1++;
                   7774:      if (cptcovn > 0) {
                   7775:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7776:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7777:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7778:        }
1.337     brouard  7779:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7780:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7781:        /* } */
                   7782:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7783:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7784:        /* } */
1.264     brouard  7785:        fprintf(fichtm,"\">");
                   7786:        
                   7787:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7788:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7789:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7790:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7791:        }
1.337     brouard  7792:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7793:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7794:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7795:        /* } */
                   7796:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7797:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7798:        /* } */
1.264     brouard  7799:        if(invalidvarcomb[k1]){
                   7800:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7801:         continue;
                   7802:        }
                   7803:        fprintf(fichtm,"</a></li>");
                   7804:      } /* cptcovn >0 */
                   7805:    }
1.317     brouard  7806:    fprintf(fichtm," \n</ul>");
1.264     brouard  7807: 
1.222     brouard  7808:    jj1=0;
1.237     brouard  7809: 
1.337     brouard  7810:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7811:      /* k1=nres; */
1.338     brouard  7812:      k1=TKresult[nres];
                   7813:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7814:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7815:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7816:    /*     continue; */
1.220     brouard  7817: 
1.222     brouard  7818:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7819:      jj1++;
                   7820:      if (cptcovn > 0) {
1.264     brouard  7821:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7822:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7823:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7824:        }
1.337     brouard  7825:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7826:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7827:        /* } */
1.264     brouard  7828:        fprintf(fichtm,"\"</a>");
                   7829:  
1.222     brouard  7830:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7831:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7832:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7833:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7834:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7835:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7836:        }
1.230     brouard  7837:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7838:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7839:        if(invalidvarcomb[k1]){
                   7840:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7841:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7842:         continue;
                   7843:        }
                   7844:      }
                   7845:      /* aij, bij */
1.259     brouard  7846:      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  7847: <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  7848:      /* Pij */
1.241     brouard  7849:      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> \
                   7850: <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  7851:      /* Quasi-incidences */
                   7852:      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  7853:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7854:  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  7855: 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> \
                   7856: <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  7857:      /* Survival functions (period) in state j */
                   7858:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7859:        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);
                   7860:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7861:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7862:      }
                   7863:      /* State specific survival functions (period) */
                   7864:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7865:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7866:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7867:  <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);
                   7868:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7869:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7870:      }
1.288     brouard  7871:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7872:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7873:        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  7874:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7875:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7876:      }
1.296     brouard  7877:      if(prevbcast==1){
1.288     brouard  7878:        /* Backward prevalence in each health state */
1.222     brouard  7879:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7880:         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);
                   7881:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7882:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7883:        }
1.217     brouard  7884:      }
1.222     brouard  7885:      if(prevfcast==1){
1.288     brouard  7886:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7887:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7888:         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);
                   7889:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7890:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7891:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7892:        }
                   7893:      }
1.296     brouard  7894:      if(prevbcast==1){
1.268     brouard  7895:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7896:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7897:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7898:  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 \
                   7899:  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  7900: 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);
                   7901:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7902:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7903:        }
                   7904:      }
1.220     brouard  7905:         
1.222     brouard  7906:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7907:        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);
                   7908:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7909:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7910:      }
                   7911:      /* } /\* end i1 *\/ */
1.337     brouard  7912:    }/* End k1=nres */
1.222     brouard  7913:    fprintf(fichtm,"</ul>");
1.126     brouard  7914: 
1.222     brouard  7915:    fprintf(fichtm,"\
1.126     brouard  7916: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7917:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7918:  - 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  7919: But because parameters are usually highly correlated (a higher incidence of disability \
                   7920: and a higher incidence of recovery can give very close observed transition) it might \
                   7921: be very useful to look not only at linear confidence intervals estimated from the \
                   7922: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7923: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7924: covariance matrix of the one-step probabilities. \
                   7925: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7926: 
1.222     brouard  7927:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7928:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7929:    fprintf(fichtm,"\
1.126     brouard  7930:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7931:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7932: 
1.222     brouard  7933:    fprintf(fichtm,"\
1.126     brouard  7934:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7935:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7936:    fprintf(fichtm,"\
1.126     brouard  7937:  - 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): \
                   7938:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7939:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7940:    fprintf(fichtm,"\
1.126     brouard  7941:  - (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): \
                   7942:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7943:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7944:    fprintf(fichtm,"\
1.288     brouard  7945:  - 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  7946:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7947:    fprintf(fichtm,"\
1.128     brouard  7948:  - 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  7949:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7950:    fprintf(fichtm,"\
1.288     brouard  7951:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7952:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7953: 
                   7954: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7955: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7956: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7957: /*     <br>",fileres,fileres,fileres,fileres); */
                   7958: /*  else  */
1.338     brouard  7959: /*    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  7960:    fflush(fichtm);
1.126     brouard  7961: 
1.225     brouard  7962:    m=pow(2,cptcoveff);
1.222     brouard  7963:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7964: 
1.317     brouard  7965:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7966: 
                   7967:   jj1=0;
                   7968: 
                   7969:    fprintf(fichtm," \n<ul>");
1.337     brouard  7970:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7971:      /* k1=nres; */
1.338     brouard  7972:      k1=TKresult[nres];
1.337     brouard  7973:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7974:      /* if(m != 1 && TKresult[nres]!= k1) */
                   7975:      /*   continue; */
1.317     brouard  7976:      jj1++;
                   7977:      if (cptcovn > 0) {
                   7978:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  7979:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7980:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7981:        }
                   7982:        fprintf(fichtm,"\">");
                   7983:        
                   7984:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7985:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7986:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7987:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7988:        }
                   7989:        if(invalidvarcomb[k1]){
                   7990:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7991:         continue;
                   7992:        }
                   7993:        fprintf(fichtm,"</a></li>");
                   7994:      } /* cptcovn >0 */
1.337     brouard  7995:    } /* End nres */
1.317     brouard  7996:    fprintf(fichtm," \n</ul>");
                   7997: 
1.222     brouard  7998:    jj1=0;
1.237     brouard  7999: 
1.241     brouard  8000:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8001:      /* k1=nres; */
1.338     brouard  8002:      k1=TKresult[nres];
                   8003:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8004:      /* for(k1=1; k1<=m;k1++){ */
                   8005:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8006:      /*   continue; */
1.222     brouard  8007:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8008:      jj1++;
1.126     brouard  8009:      if (cptcovn > 0) {
1.317     brouard  8010:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8011:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8012:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8013:        }
                   8014:        fprintf(fichtm,"\"</a>");
                   8015:        
1.126     brouard  8016:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8017:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8018:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8019:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8020:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8021:        }
1.237     brouard  8022: 
1.338     brouard  8023:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8024: 
1.222     brouard  8025:        if(invalidvarcomb[k1]){
                   8026:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8027:         continue;
                   8028:        }
1.337     brouard  8029:      } /* If cptcovn >0 */
1.126     brouard  8030:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8031:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8032: 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);
                   8033:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8034:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8035:      }
                   8036:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8037: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8038: true period expectancies (those weighted with period prevalences are also\
                   8039:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8040:  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);
                   8041:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8042:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8043:      /* } /\* end i1 *\/ */
1.241     brouard  8044:   }/* End nres */
1.222     brouard  8045:    fprintf(fichtm,"</ul>");
                   8046:    fflush(fichtm);
1.126     brouard  8047: }
                   8048: 
                   8049: /******************* Gnuplot file **************/
1.296     brouard  8050: 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  8051: 
                   8052:   char dirfileres[132],optfileres[132];
1.264     brouard  8053:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  8054:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
1.211     brouard  8055:   int lv=0, vlv=0, kl=0;
1.130     brouard  8056:   int ng=0;
1.201     brouard  8057:   int vpopbased;
1.223     brouard  8058:   int ioffset; /* variable offset for columns */
1.270     brouard  8059:   int iyearc=1; /* variable column for year of projection  */
                   8060:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8061:   int nres=0; /* Index of resultline */
1.266     brouard  8062:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8063: 
1.126     brouard  8064: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8065: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8066: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8067: /*   } */
                   8068: 
                   8069:   /*#ifdef windows */
                   8070:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8071:   /*#endif */
1.225     brouard  8072:   m=pow(2,cptcoveff);
1.126     brouard  8073: 
1.274     brouard  8074:   /* diagram of the model */
                   8075:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8076:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8077:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8078:   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);
                   8079: 
                   8080:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=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);
                   8081:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8082:   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);
                   8083:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8084:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8085:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8086:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8087: 
1.202     brouard  8088:   /* Contribution to likelihood */
                   8089:   /* Plot the probability implied in the likelihood */
1.223     brouard  8090:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8091:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8092:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8093:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8094: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8095:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8096: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8097:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8098:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8099:   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));
                   8100:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8101:   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));
                   8102:   for (i=1; i<= nlstate ; i ++) {
                   8103:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8104:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8105:     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);
                   8106:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8107:       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);
                   8108:     }
                   8109:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8110:   }
                   8111:   /* 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 */               
                   8112:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8113:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8114:   fprintf(ficgp,"\nset out;unset log\n");
                   8115:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8116: 
1.126     brouard  8117:   strcpy(dirfileres,optionfilefiname);
                   8118:   strcpy(optfileres,"vpl");
1.223     brouard  8119:   /* 1eme*/
1.238     brouard  8120:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8121:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8122:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8123:        k1=TKresult[nres];
1.338     brouard  8124:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8125:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8126:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8127:        /*   continue; */
1.238     brouard  8128:        /* We are interested in selected combination by the resultline */
1.246     brouard  8129:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8130:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8131:        strcpy(gplotlabel,"(");
1.337     brouard  8132:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8133:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8134:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8135: 
                   8136:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8137:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8138:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8139:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8140:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8141:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8142:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8143:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8144:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8145:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8146:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8147:        /* } */
                   8148:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8149:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8150:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8151:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8152:        }
                   8153:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8154:        /* printf("\n#\n"); */
1.238     brouard  8155:        fprintf(ficgp,"\n#\n");
                   8156:        if(invalidvarcomb[k1]){
1.260     brouard  8157:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8158:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8159:          continue;
                   8160:        }
1.235     brouard  8161:       
1.241     brouard  8162:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8163:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8164:        /* 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  8165:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8166:        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);
                   8167:        /* 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); */
                   8168:       /* k1-1 error should be nres-1*/
1.238     brouard  8169:        for (i=1; i<= nlstate ; i ++) {
                   8170:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8171:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8172:        }
1.288     brouard  8173:        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  8174:        for (i=1; i<= nlstate ; i ++) {
                   8175:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8176:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8177:        } 
1.260     brouard  8178:        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  8179:        for (i=1; i<= nlstate ; i ++) {
                   8180:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8181:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8182:        }  
1.265     brouard  8183:        /* 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)); */
                   8184:        
                   8185:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8186:         if(cptcoveff ==0){
1.271     brouard  8187:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8188:        }else{
                   8189:          kl=0;
                   8190:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8191:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8192:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8193:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8194:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8195:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8196:            vlv= nbcode[Tvaraff[k]][lv];
                   8197:            kl++;
                   8198:            /* 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 *\/ */
                   8199:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8200:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8201:            /* ''  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*/
                   8202:            if(k==cptcoveff){
                   8203:              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], \
                   8204:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8205:            }else{
                   8206:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8207:              kl++;
                   8208:            }
                   8209:          } /* end covariate */
                   8210:        } /* end if no covariate */
                   8211: 
1.296     brouard  8212:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8213:          /* 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  8214:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8215:          if(cptcoveff ==0){
1.245     brouard  8216:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8217:          }else{
                   8218:            kl=0;
                   8219:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8220:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8221:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8222:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8223:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8224:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8225:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8226:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8227:              kl++;
1.238     brouard  8228:              /* 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 *\/ */
                   8229:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8230:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8231:              /* ''  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*/
                   8232:              if(k==cptcoveff){
1.245     brouard  8233:                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  8234:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8235:              }else{
1.332     brouard  8236:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8237:                kl++;
                   8238:              }
                   8239:            } /* end covariate */
                   8240:          } /* end if no covariate */
1.296     brouard  8241:          if(prevbcast == 1){
1.268     brouard  8242:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8243:            /* k1-1 error should be nres-1*/
                   8244:            for (i=1; i<= nlstate ; i ++) {
                   8245:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8246:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8247:            }
1.271     brouard  8248:            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  8249:            for (i=1; i<= nlstate ; i ++) {
                   8250:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8251:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8252:            } 
1.276     brouard  8253:            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  8254:            for (i=1; i<= nlstate ; i ++) {
                   8255:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8256:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8257:            } 
1.274     brouard  8258:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8259:          } /* end if backprojcast */
1.296     brouard  8260:        } /* end if prevbcast */
1.276     brouard  8261:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8262:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8263:       } /* nres */
1.337     brouard  8264:     /* } /\* k1 *\/ */
1.201     brouard  8265:   } /* cpt */
1.235     brouard  8266: 
                   8267:   
1.126     brouard  8268:   /*2 eme*/
1.337     brouard  8269:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8270:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8271:       k1=TKresult[nres];
1.338     brouard  8272:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8273:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8274:       /*       continue; */
1.238     brouard  8275:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8276:       strcpy(gplotlabel,"(");
1.337     brouard  8277:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8278:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8279:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8280:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8281:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8282:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8283:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8284:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8285:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8286:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8287:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8288:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8289:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8290:       /* } */
                   8291:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8292:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8293:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8294:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8295:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8296:       }
1.264     brouard  8297:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8298:       fprintf(ficgp,"\n#\n");
1.223     brouard  8299:       if(invalidvarcomb[k1]){
                   8300:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8301:        continue;
                   8302:       }
1.219     brouard  8303:                        
1.241     brouard  8304:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8305:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8306:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8307:        if(vpopbased==0){
1.238     brouard  8308:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8309:        }else
1.238     brouard  8310:          fprintf(ficgp,"\nreplot ");
                   8311:        for (i=1; i<= nlstate+1 ; i ++) {
                   8312:          k=2*i;
1.261     brouard  8313:          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  8314:          for (j=1; j<= nlstate+1 ; j ++) {
                   8315:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8316:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8317:          }   
                   8318:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8319:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8320:          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  8321:          for (j=1; j<= nlstate+1 ; j ++) {
                   8322:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8323:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8324:          }   
                   8325:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8326:          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  8327:          for (j=1; j<= nlstate+1 ; j ++) {
                   8328:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8329:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8330:          }   
                   8331:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8332:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8333:        } /* state */
                   8334:       } /* vpopbased */
1.264     brouard  8335:       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  8336:     } /* end nres */
1.337     brouard  8337:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8338:        
                   8339:        
                   8340:   /*3eme*/
1.337     brouard  8341:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8342:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8343:       k1=TKresult[nres];
1.338     brouard  8344:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8345:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8346:       /*       continue; */
1.238     brouard  8347: 
1.332     brouard  8348:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8349:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8350:        strcpy(gplotlabel,"(");
1.337     brouard  8351:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8352:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8353:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8354:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8355:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8356:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8357:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8358:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8359:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8360:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8361:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8362:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8363:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8364:        /* } */
                   8365:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8366:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8367:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8368:        }
1.264     brouard  8369:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8370:        fprintf(ficgp,"\n#\n");
                   8371:        if(invalidvarcomb[k1]){
                   8372:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8373:          continue;
                   8374:        }
                   8375:                        
                   8376:        /*       k=2+nlstate*(2*cpt-2); */
                   8377:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8378:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8379:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8380:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8381: 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  8382:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8383:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8384:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8385:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8386:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8387:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8388:                                
1.238     brouard  8389:        */
                   8390:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8391:          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  8392:          /*    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  8393:                                
1.238     brouard  8394:        } 
1.261     brouard  8395:        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  8396:       }
1.264     brouard  8397:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8398:     } /* end nres */
1.337     brouard  8399:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8400:   
1.223     brouard  8401:   /* 4eme */
1.201     brouard  8402:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8403:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8404:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8405:       k1=TKresult[nres];
1.338     brouard  8406:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8407:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8408:       /*       continue; */
1.238     brouard  8409:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8410:        strcpy(gplotlabel,"(");
1.337     brouard  8411:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8412:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8413:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8414:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8415:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8416:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8417:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8418:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8419:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8420:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8421:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8422:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8423:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8424:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8425:        /* } */
                   8426:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8427:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8428:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8429:        }       
1.264     brouard  8430:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8431:        fprintf(ficgp,"\n#\n");
                   8432:        if(invalidvarcomb[k1]){
                   8433:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8434:          continue;
1.223     brouard  8435:        }
1.238     brouard  8436:       
1.241     brouard  8437:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8438:        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  8439:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8440: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8441:        k=3;
                   8442:        for (i=1; i<= nlstate ; i ++){
                   8443:          if(i==1){
                   8444:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8445:          }else{
                   8446:            fprintf(ficgp,", '' ");
                   8447:          }
                   8448:          l=(nlstate+ndeath)*(i-1)+1;
                   8449:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8450:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8451:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8452:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8453:        } /* nlstate */
1.264     brouard  8454:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8455:       } /* end cpt state*/ 
                   8456:     } /* end nres */
1.337     brouard  8457:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8458: 
1.220     brouard  8459: /* 5eme */
1.201     brouard  8460:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8461:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8462:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8463:       k1=TKresult[nres];
1.338     brouard  8464:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8465:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8466:       /*       continue; */
1.238     brouard  8467:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8468:        strcpy(gplotlabel,"(");
1.238     brouard  8469:        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  8470:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8471:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8472:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8473:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8474:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8475:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8476:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8477:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8478:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8479:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8480:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8481:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8482:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8483:        /* } */
                   8484:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8485:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8486:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8487:        }       
1.264     brouard  8488:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8489:        fprintf(ficgp,"\n#\n");
                   8490:        if(invalidvarcomb[k1]){
                   8491:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8492:          continue;
                   8493:        }
1.227     brouard  8494:       
1.241     brouard  8495:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8496:        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  8497:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8498: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8499:        k=3;
                   8500:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8501:          if(j==1)
                   8502:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8503:          else
                   8504:            fprintf(ficgp,", '' ");
                   8505:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8506:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8507:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8508:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8509:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8510:        } /* nlstate */
                   8511:        fprintf(ficgp,", '' ");
                   8512:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8513:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8514:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8515:          if(j < nlstate)
                   8516:            fprintf(ficgp,"$%d +",k+l);
                   8517:          else
                   8518:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8519:        }
1.264     brouard  8520:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8521:       } /* end cpt state*/ 
1.337     brouard  8522:     /* } /\* end covariate *\/   */
1.238     brouard  8523:   } /* end nres */
1.227     brouard  8524:   
1.220     brouard  8525: /* 6eme */
1.202     brouard  8526:   /* CV preval stable (period) for each covariate */
1.337     brouard  8527:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8528:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8529:      k1=TKresult[nres];
1.338     brouard  8530:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8531:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8532:      /*  continue; */
1.255     brouard  8533:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8534:       strcpy(gplotlabel,"(");      
1.288     brouard  8535:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8536:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8537:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8538:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8539:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8540:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8541:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8542:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8543:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8544:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8545:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8546:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8547:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8548:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8549:       /* } */
                   8550:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8551:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8552:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8553:       }        
1.264     brouard  8554:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8555:       fprintf(ficgp,"\n#\n");
1.223     brouard  8556:       if(invalidvarcomb[k1]){
1.227     brouard  8557:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8558:        continue;
1.223     brouard  8559:       }
1.227     brouard  8560:       
1.241     brouard  8561:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8562:       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  8563:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8564: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8565:       k=3; /* Offset */
1.255     brouard  8566:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8567:        if(i==1)
                   8568:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8569:        else
                   8570:          fprintf(ficgp,", '' ");
1.255     brouard  8571:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8572:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8573:        for (j=2; j<= nlstate ; j ++)
                   8574:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8575:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8576:       } /* nlstate */
1.264     brouard  8577:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8578:     } /* end cpt state*/ 
                   8579:   } /* end covariate */  
1.227     brouard  8580:   
                   8581:   
1.220     brouard  8582: /* 7eme */
1.296     brouard  8583:   if(prevbcast == 1){
1.288     brouard  8584:     /* CV backward prevalence  for each covariate */
1.337     brouard  8585:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8586:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8587:       k1=TKresult[nres];
1.338     brouard  8588:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8589:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8590:       /*       continue; */
1.268     brouard  8591:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8592:        strcpy(gplotlabel,"(");      
1.288     brouard  8593:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8594:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8595:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8596:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8597:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8598:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8599:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8600:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8601:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8602:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8603:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8604:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8605:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8606:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8607:        /* } */
                   8608:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8609:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8610:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8611:        }       
1.264     brouard  8612:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8613:        fprintf(ficgp,"\n#\n");
                   8614:        if(invalidvarcomb[k1]){
                   8615:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8616:          continue;
                   8617:        }
                   8618:        
1.241     brouard  8619:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8620:        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  8621:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8622: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8623:        k=3; /* Offset */
1.268     brouard  8624:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8625:          if(i==1)
                   8626:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8627:          else
                   8628:            fprintf(ficgp,", '' ");
                   8629:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8630:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8631:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8632:          /* 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  8633:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8634:          /* for (j=2; j<= nlstate ; j ++) */
                   8635:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8636:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8637:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8638:        } /* nlstate */
1.264     brouard  8639:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8640:       } /* end cpt state*/ 
                   8641:     } /* end covariate */  
1.296     brouard  8642:   } /* End if prevbcast */
1.218     brouard  8643:   
1.223     brouard  8644:   /* 8eme */
1.218     brouard  8645:   if(prevfcast==1){
1.288     brouard  8646:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8647:     
1.337     brouard  8648:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8649:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8650:       k1=TKresult[nres];
1.338     brouard  8651:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8652:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8653:       /*       continue; */
1.211     brouard  8654:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8655:        strcpy(gplotlabel,"(");      
1.288     brouard  8656:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8657:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8658:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8659:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8660:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8661:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8662:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8663:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8664:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8665:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8666:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8667:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8668:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8669:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8670:        /* } */
                   8671:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8672:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8673:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8674:        }       
1.264     brouard  8675:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8676:        fprintf(ficgp,"\n#\n");
                   8677:        if(invalidvarcomb[k1]){
                   8678:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8679:          continue;
                   8680:        }
                   8681:        
                   8682:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8683:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8684:        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  8685:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8686: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8687: 
                   8688:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8689:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8690:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8691:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8692:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8693:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8694:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8695:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8696:          if(i==istart){
1.227     brouard  8697:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8698:          }else{
                   8699:            fprintf(ficgp,",\\\n '' ");
                   8700:          }
                   8701:          if(cptcoveff ==0){ /* No covariate */
                   8702:            ioffset=2; /* Age is in 2 */
                   8703:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8704:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8705:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8706:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8707:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8708:            if(i==nlstate+1){
1.270     brouard  8709:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8710:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8711:              fprintf(ficgp,",\\\n '' ");
                   8712:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8713:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8714:                     offyear,                           \
1.268     brouard  8715:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8716:            }else
1.227     brouard  8717:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8718:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8719:          }else{ /* more than 2 covariates */
1.270     brouard  8720:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8721:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8722:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8723:            iyearc=ioffset-1;
                   8724:            iagec=ioffset;
1.227     brouard  8725:            fprintf(ficgp," u %d:(",ioffset); 
                   8726:            kl=0;
                   8727:            strcpy(gplotcondition,"(");
                   8728:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8729:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8730:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8731:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8732:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8733:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8734:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8735:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8736:              kl++;
                   8737:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8738:              kl++;
                   8739:              if(k <cptcoveff && cptcoveff>1)
                   8740:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8741:            }
                   8742:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8743:            /* 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 *\/ */
                   8744:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8745:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8746:            /* ''  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*/
                   8747:            if(i==nlstate+1){
1.270     brouard  8748:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8749:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8750:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8751:              fprintf(ficgp," u %d:(",iagec); 
                   8752:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8753:                      iyearc, iagec, offyear,                           \
                   8754:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8755: /*  '' 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  8756:            }else{
                   8757:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8758:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8759:            }
                   8760:          } /* end if covariate */
                   8761:        } /* nlstate */
1.264     brouard  8762:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8763:       } /* end cpt state*/
                   8764:     } /* end covariate */
                   8765:   } /* End if prevfcast */
1.227     brouard  8766:   
1.296     brouard  8767:   if(prevbcast==1){
1.268     brouard  8768:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8769:     
1.337     brouard  8770:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8771:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8772:      k1=TKresult[nres];
1.338     brouard  8773:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8774:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8775:        /*      continue; */
1.268     brouard  8776:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8777:        strcpy(gplotlabel,"(");      
                   8778:        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  8779:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8780:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8781:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8782:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8783:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8784:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8785:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8786:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8787:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8788:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8789:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8790:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8791:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8792:        /* } */
                   8793:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8794:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8795:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8796:        }       
                   8797:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8798:        fprintf(ficgp,"\n#\n");
                   8799:        if(invalidvarcomb[k1]){
                   8800:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8801:          continue;
                   8802:        }
                   8803:        
                   8804:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8805:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8806:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8807:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8808: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8809: 
                   8810:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8811:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8812:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8813:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8814:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8815:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8816:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8817:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8818:          if(i==istart){
                   8819:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8820:          }else{
                   8821:            fprintf(ficgp,",\\\n '' ");
                   8822:          }
                   8823:          if(cptcoveff ==0){ /* No covariate */
                   8824:            ioffset=2; /* Age is in 2 */
                   8825:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8826:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8827:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8828:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8829:            fprintf(ficgp," u %d:(", ioffset); 
                   8830:            if(i==nlstate+1){
1.270     brouard  8831:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8832:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8833:              fprintf(ficgp,",\\\n '' ");
                   8834:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8835:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8836:                     offbyear,                          \
                   8837:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8838:            }else
                   8839:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8840:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8841:          }else{ /* more than 2 covariates */
1.270     brouard  8842:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8843:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8844:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8845:            iyearc=ioffset-1;
                   8846:            iagec=ioffset;
1.268     brouard  8847:            fprintf(ficgp," u %d:(",ioffset); 
                   8848:            kl=0;
                   8849:            strcpy(gplotcondition,"(");
1.337     brouard  8850:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  8851:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  8852:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   8853:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8854:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8855:                lv=Tvresult[nres][k];
                   8856:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   8857:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8858:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8859:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8860:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8861:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8862:                kl++;
                   8863:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   8864:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   8865:                kl++;
1.338     brouard  8866:                if(k <cptcovs && cptcovs>1)
1.337     brouard  8867:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8868:              }
1.268     brouard  8869:            }
                   8870:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8871:            /* 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 *\/ */
                   8872:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8873:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8874:            /* ''  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*/
                   8875:            if(i==nlstate+1){
1.270     brouard  8876:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8877:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8878:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8879:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8880:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8881:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8882:                      iyearc,iagec,offbyear,                            \
                   8883:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8884: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8885:            }else{
                   8886:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8887:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8888:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8889:            }
                   8890:          } /* end if covariate */
                   8891:        } /* nlstate */
                   8892:        fprintf(ficgp,"\nset out; unset label;\n");
                   8893:       } /* end cpt state*/
                   8894:     } /* end covariate */
1.296     brouard  8895:   } /* End if prevbcast */
1.268     brouard  8896:   
1.227     brouard  8897:   
1.238     brouard  8898:   /* 9eme writing MLE parameters */
                   8899:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8900:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8901:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8902:     for(k=1; k <=(nlstate+ndeath); k++){
                   8903:       if (k != i) {
1.227     brouard  8904:        fprintf(ficgp,"#   current state %d\n",k);
                   8905:        for(j=1; j <=ncovmodel; j++){
                   8906:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8907:          jk++; 
                   8908:        }
                   8909:        fprintf(ficgp,"\n");
1.126     brouard  8910:       }
                   8911:     }
1.223     brouard  8912:   }
1.187     brouard  8913:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8914:   
1.145     brouard  8915:   /*goto avoid;*/
1.238     brouard  8916:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8917:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8918:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8919:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8920:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8921:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8922:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8923:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8924:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8925:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8926:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8927:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8928:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8929:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8930:   fprintf(ficgp,"#\n");
1.223     brouard  8931:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8932:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  8933:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  8934:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8935:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  8936:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  8937:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8938:      /* k1=nres; */
1.338     brouard  8939:       k1=TKresult[nres];
                   8940:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8941:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  8942:       strcpy(gplotlabel,"(");
1.276     brouard  8943:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  8944:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8945:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   8946:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   8947:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8948:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8949:       }
                   8950:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8951:       /*       continue; */
                   8952:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   8953:       /* strcpy(gplotlabel,"("); */
                   8954:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   8955:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8956:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8957:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8958:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8959:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8960:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8961:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8962:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8963:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8964:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8965:       /* } */
                   8966:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8967:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8968:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8969:       /* }      */
1.264     brouard  8970:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8971:       fprintf(ficgp,"\n#\n");
1.264     brouard  8972:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8973:       fprintf(ficgp,"\nset key outside ");
                   8974:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8975:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8976:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8977:       if (ng==1){
                   8978:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8979:        fprintf(ficgp,"\nunset log y");
                   8980:       }else if (ng==2){
                   8981:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8982:        fprintf(ficgp,"\nset log y");
                   8983:       }else if (ng==3){
                   8984:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8985:        fprintf(ficgp,"\nset log y");
                   8986:       }else
                   8987:        fprintf(ficgp,"\nunset title ");
                   8988:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8989:       i=1;
                   8990:       for(k2=1; k2<=nlstate; k2++) {
                   8991:        k3=i;
                   8992:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8993:          if (k != k2){
                   8994:            switch( ng) {
                   8995:            case 1:
                   8996:              if(nagesqr==0)
                   8997:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8998:              else /* nagesqr =1 */
                   8999:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9000:              break;
                   9001:            case 2: /* ng=2 */
                   9002:              if(nagesqr==0)
                   9003:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9004:              else /* nagesqr =1 */
                   9005:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9006:              break;
                   9007:            case 3:
                   9008:              if(nagesqr==0)
                   9009:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9010:              else /* nagesqr =1 */
                   9011:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9012:              break;
                   9013:            }
                   9014:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9015:            ijp=1; /* product no age */
                   9016:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9017:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9018:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9019:              switch(Typevar[j]){
                   9020:              case 1:
                   9021:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9022:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9023:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9024:                      if(DummyV[j]==0){/* Bug valgrind */
                   9025:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9026:                      }else{ /* quantitative */
                   9027:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9028:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9029:                      }
                   9030:                      ij++;
1.268     brouard  9031:                    }
1.237     brouard  9032:                  }
1.329     brouard  9033:                }
                   9034:                break;
                   9035:              case 2:
                   9036:                if(cptcovprod >0){
                   9037:                  if(j==Tprod[ijp]) { /* */ 
                   9038:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9039:                    if(ijp <=cptcovprod) { /* Product */
                   9040:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9041:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9042:                          /* 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)]); */
                   9043:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9044:                        }else{ /* Vn is dummy and Vm is quanti */
                   9045:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9046:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9047:                        }
                   9048:                      }else{ /* Vn*Vm Vn is quanti */
                   9049:                        if(DummyV[Tvard[ijp][2]]==0){
                   9050:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9051:                        }else{ /* Both quanti */
                   9052:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9053:                        }
1.268     brouard  9054:                      }
1.329     brouard  9055:                      ijp++;
1.237     brouard  9056:                    }
1.329     brouard  9057:                  } /* end Tprod */
                   9058:                }
                   9059:                break;
                   9060:              case 0:
                   9061:                /* simple covariate */
1.264     brouard  9062:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9063:                if(Dummy[j]==0){
                   9064:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9065:                }else{ /* quantitative */
                   9066:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9067:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9068:                }
1.329     brouard  9069:               /* end simple */
                   9070:                break;
                   9071:              default:
                   9072:                break;
                   9073:              } /* end switch */
1.237     brouard  9074:            } /* end j */
1.329     brouard  9075:          }else{ /* k=k2 */
                   9076:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9077:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9078:            }else
                   9079:              i=i-ncovmodel;
1.223     brouard  9080:          }
1.227     brouard  9081:          
1.223     brouard  9082:          if(ng != 1){
                   9083:            fprintf(ficgp,")/(1");
1.227     brouard  9084:            
1.264     brouard  9085:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9086:              if(nagesqr==0)
1.264     brouard  9087:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9088:              else /* nagesqr =1 */
1.264     brouard  9089:                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  9090:               
1.223     brouard  9091:              ij=1;
1.329     brouard  9092:              ijp=1;
                   9093:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9094:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9095:                switch(Typevar[j]){
                   9096:                case 1:
                   9097:                  if(cptcovage >0){ 
                   9098:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9099:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9100:                        if(DummyV[j]==0){/* Bug valgrind */
                   9101:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9102:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9103:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9104:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9105:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9106:                        }else{ /* quantitative */
                   9107:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9108:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9109:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9110:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9111:                        }
                   9112:                        ij++;
                   9113:                      }
                   9114:                    }
                   9115:                  }
                   9116:                  break;
                   9117:                case 2:
                   9118:                  if(cptcovprod >0){
                   9119:                    if(j==Tprod[ijp]) { /* */ 
                   9120:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9121:                      if(ijp <=cptcovprod) { /* Product */
                   9122:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9123:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9124:                            /* 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)]); */
                   9125:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9126:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9127:                          }else{ /* Vn is dummy and Vm is quanti */
                   9128:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9129:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9130:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9131:                          }
                   9132:                        }else{ /* Vn*Vm Vn is quanti */
                   9133:                          if(DummyV[Tvard[ijp][2]]==0){
                   9134:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9135:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9136:                          }else{ /* Both quanti */
                   9137:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9138:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9139:                          } 
                   9140:                        }
                   9141:                        ijp++;
                   9142:                      }
                   9143:                    } /* end Tprod */
                   9144:                  } /* end if */
                   9145:                  break;
                   9146:                case 0: 
                   9147:                  /* simple covariate */
                   9148:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9149:                  if(Dummy[j]==0){
                   9150:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9151:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9152:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9153:                  }else{ /* quantitative */
                   9154:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9155:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9156:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9157:                  }
                   9158:                  /* end simple */
                   9159:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9160:                  break;
                   9161:                default:
                   9162:                  break;
                   9163:                } /* end switch */
1.223     brouard  9164:              }
                   9165:              fprintf(ficgp,")");
                   9166:            }
                   9167:            fprintf(ficgp,")");
                   9168:            if(ng ==2)
1.276     brouard  9169:              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  9170:            else /* ng= 3 */
1.276     brouard  9171:              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  9172:           }else{ /* end ng <> 1 */
1.223     brouard  9173:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9174:              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  9175:          }
                   9176:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9177:            fprintf(ficgp,",");
                   9178:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9179:            fprintf(ficgp,",");
                   9180:          i=i+ncovmodel;
                   9181:        } /* end k */
                   9182:       } /* end k2 */
1.276     brouard  9183:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9184:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9185:     } /* end resultline */
1.223     brouard  9186:   } /* end ng */
                   9187:   /* avoid: */
                   9188:   fflush(ficgp); 
1.126     brouard  9189: }  /* end gnuplot */
                   9190: 
                   9191: 
                   9192: /*************** Moving average **************/
1.219     brouard  9193: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9194:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9195:    
1.222     brouard  9196:    int i, cpt, cptcod;
                   9197:    int modcovmax =1;
                   9198:    int mobilavrange, mob;
                   9199:    int iage=0;
1.288     brouard  9200:    int firstA1=0, firstA2=0;
1.222     brouard  9201: 
1.266     brouard  9202:    double sum=0., sumr=0.;
1.222     brouard  9203:    double age;
1.266     brouard  9204:    double *sumnewp, *sumnewm, *sumnewmr;
                   9205:    double *agemingood, *agemaxgood; 
                   9206:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9207:   
                   9208:   
1.278     brouard  9209:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9210:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9211: 
                   9212:    sumnewp = vector(1,ncovcombmax);
                   9213:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9214:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9215:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9216:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9217:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9218:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9219: 
                   9220:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9221:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9222:      sumnewp[cptcod]=0.;
1.266     brouard  9223:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9224:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9225:    }
                   9226:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9227:   
1.266     brouard  9228:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9229:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9230:      else mobilavrange=mobilav;
                   9231:      for (age=bage; age<=fage; age++)
                   9232:        for (i=1; i<=nlstate;i++)
                   9233:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9234:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9235:      /* We keep the original values on the extreme ages bage, fage and for 
                   9236:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9237:        we use a 5 terms etc. until the borders are no more concerned. 
                   9238:      */ 
                   9239:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9240:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9241:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9242:           sumnewm[cptcod]=0.;
                   9243:           for (i=1; i<=nlstate;i++){
1.222     brouard  9244:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9245:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9246:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9247:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9248:             }
                   9249:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9250:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9251:           } /* end i */
                   9252:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9253:         } /* end cptcod */
1.222     brouard  9254:        }/* end age */
                   9255:      }/* end mob */
1.266     brouard  9256:    }else{
                   9257:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9258:      return -1;
1.266     brouard  9259:    }
                   9260: 
                   9261:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9262:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9263:      if(invalidvarcomb[cptcod]){
                   9264:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9265:        continue;
                   9266:      }
1.219     brouard  9267: 
1.266     brouard  9268:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9269:        sumnewm[cptcod]=0.;
                   9270:        sumnewmr[cptcod]=0.;
                   9271:        for (i=1; i<=nlstate;i++){
                   9272:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9273:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9274:        }
                   9275:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9276:         agemingoodr[cptcod]=age;
                   9277:        }
                   9278:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9279:           agemingood[cptcod]=age;
                   9280:        }
                   9281:      } /* age */
                   9282:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9283:        sumnewm[cptcod]=0.;
1.266     brouard  9284:        sumnewmr[cptcod]=0.;
1.222     brouard  9285:        for (i=1; i<=nlstate;i++){
                   9286:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9287:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9288:        }
                   9289:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9290:         agemaxgoodr[cptcod]=age;
1.222     brouard  9291:        }
                   9292:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9293:         agemaxgood[cptcod]=age;
                   9294:        }
                   9295:      } /* age */
                   9296:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9297:      /* but they will change */
1.288     brouard  9298:      firstA1=0;firstA2=0;
1.266     brouard  9299:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9300:        sumnewm[cptcod]=0.;
                   9301:        sumnewmr[cptcod]=0.;
                   9302:        for (i=1; i<=nlstate;i++){
                   9303:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9304:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9305:        }
                   9306:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9307:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9308:           agemaxgoodr[cptcod]=age;  /* age min */
                   9309:           for (i=1; i<=nlstate;i++)
                   9310:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9311:         }else{ /* bad we change the value with the values of good ages */
                   9312:           for (i=1; i<=nlstate;i++){
                   9313:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9314:           } /* i */
                   9315:         } /* end bad */
                   9316:        }else{
                   9317:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9318:           agemaxgood[cptcod]=age;
                   9319:         }else{ /* bad we change the value with the values of good ages */
                   9320:           for (i=1; i<=nlstate;i++){
                   9321:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9322:           } /* i */
                   9323:         } /* end bad */
                   9324:        }/* end else */
                   9325:        sum=0.;sumr=0.;
                   9326:        for (i=1; i<=nlstate;i++){
                   9327:         sum+=mobaverage[(int)age][i][cptcod];
                   9328:         sumr+=probs[(int)age][i][cptcod];
                   9329:        }
                   9330:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9331:         if(!firstA1){
                   9332:           firstA1=1;
                   9333:           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);
                   9334:         }
                   9335:         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  9336:        } /* end bad */
                   9337:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9338:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9339:         if(!firstA2){
                   9340:           firstA2=1;
                   9341:           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);
                   9342:         }
                   9343:         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  9344:        } /* end bad */
                   9345:      }/* age */
1.266     brouard  9346: 
                   9347:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9348:        sumnewm[cptcod]=0.;
1.266     brouard  9349:        sumnewmr[cptcod]=0.;
1.222     brouard  9350:        for (i=1; i<=nlstate;i++){
                   9351:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9352:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9353:        } 
                   9354:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9355:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9356:           agemingoodr[cptcod]=age;
                   9357:           for (i=1; i<=nlstate;i++)
                   9358:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9359:         }else{ /* bad we change the value with the values of good ages */
                   9360:           for (i=1; i<=nlstate;i++){
                   9361:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9362:           } /* i */
                   9363:         } /* end bad */
                   9364:        }else{
                   9365:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9366:           agemingood[cptcod]=age;
                   9367:         }else{ /* bad */
                   9368:           for (i=1; i<=nlstate;i++){
                   9369:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9370:           } /* i */
                   9371:         } /* end bad */
                   9372:        }/* end else */
                   9373:        sum=0.;sumr=0.;
                   9374:        for (i=1; i<=nlstate;i++){
                   9375:         sum+=mobaverage[(int)age][i][cptcod];
                   9376:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9377:        }
1.266     brouard  9378:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9379:         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  9380:        } /* end bad */
                   9381:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9382:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9383:         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  9384:        } /* end bad */
                   9385:      }/* age */
1.266     brouard  9386: 
1.222     brouard  9387:                
                   9388:      for (age=bage; age<=fage; age++){
1.235     brouard  9389:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9390:        sumnewp[cptcod]=0.;
                   9391:        sumnewm[cptcod]=0.;
                   9392:        for (i=1; i<=nlstate;i++){
                   9393:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9394:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9395:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9396:        }
                   9397:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9398:      }
                   9399:      /* printf("\n"); */
                   9400:      /* } */
1.266     brouard  9401: 
1.222     brouard  9402:      /* brutal averaging */
1.266     brouard  9403:      /* for (i=1; i<=nlstate;i++){ */
                   9404:      /*   for (age=1; age<=bage; age++){ */
                   9405:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9406:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9407:      /*   }     */
                   9408:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9409:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9410:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9411:      /*   } */
                   9412:      /* } /\* end i status *\/ */
                   9413:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9414:      /*   for (age=1; age<=AGESUP; age++){ */
                   9415:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9416:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9417:      /*   } */
                   9418:      /* } */
1.222     brouard  9419:    }/* end cptcod */
1.266     brouard  9420:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9421:    free_vector(agemaxgood,1, ncovcombmax);
                   9422:    free_vector(agemingood,1, ncovcombmax);
                   9423:    free_vector(agemingoodr,1, ncovcombmax);
                   9424:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9425:    free_vector(sumnewm,1, ncovcombmax);
                   9426:    free_vector(sumnewp,1, ncovcombmax);
                   9427:    return 0;
                   9428:  }/* End movingaverage */
1.218     brouard  9429:  
1.126     brouard  9430: 
1.296     brouard  9431:  
1.126     brouard  9432: /************** Forecasting ******************/
1.296     brouard  9433: /* 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)*/
                   9434: 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){
                   9435:   /* dateintemean, mean date of interviews
                   9436:      dateprojd, year, month, day of starting projection 
                   9437:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9438:      agemin, agemax range of age
                   9439:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9440:   */
1.296     brouard  9441:   /* double anprojd, mprojd, jprojd; */
                   9442:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9443:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9444:   double agec; /* generic age */
1.296     brouard  9445:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9446:   double *popeffectif,*popcount;
                   9447:   double ***p3mat;
1.218     brouard  9448:   /* double ***mobaverage; */
1.126     brouard  9449:   char fileresf[FILENAMELENGTH];
                   9450: 
                   9451:   agelim=AGESUP;
1.211     brouard  9452:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9453:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9454:      We still use firstpass and lastpass as another selection.
                   9455:   */
1.214     brouard  9456:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9457:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9458:  
1.201     brouard  9459:   strcpy(fileresf,"F_"); 
                   9460:   strcat(fileresf,fileresu);
1.126     brouard  9461:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9462:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9463:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9464:   }
1.235     brouard  9465:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9466:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9467: 
1.225     brouard  9468:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9469: 
                   9470: 
                   9471:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9472:   if (stepm<=12) stepsize=1;
                   9473:   if(estepm < stepm){
                   9474:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9475:   }
1.270     brouard  9476:   else{
                   9477:     hstepm=estepm;   
                   9478:   }
                   9479:   if(estepm > stepm){ /* Yes every two year */
                   9480:     stepsize=2;
                   9481:   }
1.296     brouard  9482:   hstepm=hstepm/stepm;
1.126     brouard  9483: 
1.296     brouard  9484:   
                   9485:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9486:   /*                              fractional in yp1 *\/ */
                   9487:   /* aintmean=yp; */
                   9488:   /* yp2=modf((yp1*12),&yp); */
                   9489:   /* mintmean=yp; */
                   9490:   /* yp1=modf((yp2*30.5),&yp); */
                   9491:   /* jintmean=yp; */
                   9492:   /* if(jintmean==0) jintmean=1; */
                   9493:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9494: 
1.296     brouard  9495: 
                   9496:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9497:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9498:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9499:   i1=pow(2,cptcoveff);
1.126     brouard  9500:   if (cptcovn < 1){i1=1;}
                   9501:   
1.296     brouard  9502:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9503:   
                   9504:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9505:   
1.126     brouard  9506: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9507:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9508:     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  9509:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9510:       continue;
1.227     brouard  9511:     if(invalidvarcomb[k]){
                   9512:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9513:       continue;
                   9514:     }
                   9515:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9516:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9517:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9518:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9519:     }
1.235     brouard  9520:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9521:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9522:     }
1.227     brouard  9523:     fprintf(ficresf," yearproj age");
                   9524:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9525:       for(i=1; i<=nlstate;i++)               
                   9526:        fprintf(ficresf," p%d%d",i,j);
                   9527:       fprintf(ficresf," wp.%d",j);
                   9528:     }
1.296     brouard  9529:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9530:       fprintf(ficresf,"\n");
1.296     brouard  9531:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9532:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9533:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9534:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9535:        nhstepm = nhstepm/hstepm; 
                   9536:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9537:        oldm=oldms;savm=savms;
1.268     brouard  9538:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9539:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9540:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9541:        for (h=0; h<=nhstepm; h++){
                   9542:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9543:            break;
                   9544:          }
                   9545:        }
                   9546:        fprintf(ficresf,"\n");
                   9547:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9548:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9549:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9550:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9551:        
                   9552:        for(j=1; j<=nlstate+ndeath;j++) {
                   9553:          ppij=0.;
                   9554:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9555:            if (mobilav>=1)
                   9556:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9557:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9558:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9559:            }
1.268     brouard  9560:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9561:          } /* end i */
                   9562:          fprintf(ficresf," %.3f", ppij);
                   9563:        }/* end j */
1.227     brouard  9564:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9565:       } /* end agec */
1.266     brouard  9566:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9567:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9568:     } /* end yearp */
                   9569:   } /* end  k */
1.219     brouard  9570:        
1.126     brouard  9571:   fclose(ficresf);
1.215     brouard  9572:   printf("End of Computing forecasting \n");
                   9573:   fprintf(ficlog,"End of Computing forecasting\n");
                   9574: 
1.126     brouard  9575: }
                   9576: 
1.269     brouard  9577: /************** Back Forecasting ******************/
1.296     brouard  9578:  /* 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){ */
                   9579:  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){
                   9580:   /* back1, year, month, day of starting backprojection
1.267     brouard  9581:      agemin, agemax range of age
                   9582:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9583:      anback2 year of end of backprojection (same day and month as back1).
                   9584:      prevacurrent and prev are prevalences.
1.267     brouard  9585:   */
                   9586:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9587:   double agec; /* generic age */
1.302     brouard  9588:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9589:   double *popeffectif,*popcount;
                   9590:   double ***p3mat;
                   9591:   /* double ***mobaverage; */
                   9592:   char fileresfb[FILENAMELENGTH];
                   9593:  
1.268     brouard  9594:   agelim=AGEINF;
1.267     brouard  9595:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9596:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9597:      We still use firstpass and lastpass as another selection.
                   9598:   */
                   9599:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9600:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9601: 
                   9602:   /*Do we need to compute prevalence again?*/
                   9603: 
                   9604:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9605:   
                   9606:   strcpy(fileresfb,"FB_");
                   9607:   strcat(fileresfb,fileresu);
                   9608:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9609:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9610:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9611:   }
                   9612:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9613:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9614:   
                   9615:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9616:   
                   9617:    
                   9618:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9619:   if (stepm<=12) stepsize=1;
                   9620:   if(estepm < stepm){
                   9621:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9622:   }
1.270     brouard  9623:   else{
                   9624:     hstepm=estepm;   
                   9625:   }
                   9626:   if(estepm >= stepm){ /* Yes every two year */
                   9627:     stepsize=2;
                   9628:   }
1.267     brouard  9629:   
                   9630:   hstepm=hstepm/stepm;
1.296     brouard  9631:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9632:   /*                              fractional in yp1 *\/ */
                   9633:   /* aintmean=yp; */
                   9634:   /* yp2=modf((yp1*12),&yp); */
                   9635:   /* mintmean=yp; */
                   9636:   /* yp1=modf((yp2*30.5),&yp); */
                   9637:   /* jintmean=yp; */
                   9638:   /* if(jintmean==0) jintmean=1; */
                   9639:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9640:   
                   9641:   i1=pow(2,cptcoveff);
                   9642:   if (cptcovn < 1){i1=1;}
                   9643:   
1.296     brouard  9644:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9645:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9646:   
                   9647:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9648:   
                   9649:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9650:   for(k=1; k<=i1;k++){
                   9651:     if(i1 != 1 && TKresult[nres]!= k)
                   9652:       continue;
                   9653:     if(invalidvarcomb[k]){
                   9654:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9655:       continue;
                   9656:     }
1.268     brouard  9657:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9658:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9659:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9660:     }
                   9661:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9662:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9663:     }
                   9664:     fprintf(ficresfb," yearbproj age");
                   9665:     for(j=1; j<=nlstate+ndeath;j++){
                   9666:       for(i=1; i<=nlstate;i++)
1.268     brouard  9667:        fprintf(ficresfb," b%d%d",i,j);
                   9668:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9669:     }
1.296     brouard  9670:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9671:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9672:       fprintf(ficresfb,"\n");
1.296     brouard  9673:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9674:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9675:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9676:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9677:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9678:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9679:        nhstepm = nhstepm/hstepm;
                   9680:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9681:        oldm=oldms;savm=savms;
1.268     brouard  9682:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9683:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9684:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9685:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9686:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9687:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9688:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9689:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9690:            break;
                   9691:          }
                   9692:        }
                   9693:        fprintf(ficresfb,"\n");
                   9694:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9695:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9696:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9697:        for(i=1; i<=nlstate+ndeath;i++) {
                   9698:          ppij=0.;ppi=0.;
                   9699:          for(j=1; j<=nlstate;j++) {
                   9700:            /* if (mobilav==1) */
1.269     brouard  9701:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9702:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9703:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9704:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9705:              /* else { */
                   9706:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9707:              /* } */
1.268     brouard  9708:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9709:          } /* end j */
                   9710:          if(ppi <0.99){
                   9711:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9712:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9713:          }
                   9714:          fprintf(ficresfb," %.3f", ppij);
                   9715:        }/* end j */
1.267     brouard  9716:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9717:       } /* end agec */
                   9718:     } /* end yearp */
                   9719:   } /* end k */
1.217     brouard  9720:   
1.267     brouard  9721:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9722:   
1.267     brouard  9723:   fclose(ficresfb);
                   9724:   printf("End of Computing Back forecasting \n");
                   9725:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9726:        
1.267     brouard  9727: }
1.217     brouard  9728: 
1.269     brouard  9729: /* Variance of prevalence limit: varprlim */
                   9730:  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  9731:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9732:  
                   9733:    char fileresvpl[FILENAMELENGTH];  
                   9734:    FILE *ficresvpl;
                   9735:    double **oldm, **savm;
                   9736:    double **varpl; /* Variances of prevalence limits by age */   
                   9737:    int i1, k, nres, j ;
                   9738:    
                   9739:     strcpy(fileresvpl,"VPL_");
                   9740:     strcat(fileresvpl,fileresu);
                   9741:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9742:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9743:       exit(0);
                   9744:     }
1.288     brouard  9745:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9746:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9747:     
                   9748:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9749:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9750:     
                   9751:     i1=pow(2,cptcoveff);
                   9752:     if (cptcovn < 1){i1=1;}
                   9753: 
1.337     brouard  9754:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9755:        k=TKresult[nres];
1.338     brouard  9756:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9757:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9758:       if(i1 != 1 && TKresult[nres]!= k)
                   9759:        continue;
                   9760:       fprintf(ficresvpl,"\n#****** ");
                   9761:       printf("\n#****** ");
                   9762:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9763:       for(j=1;j<=cptcovs;j++) {
                   9764:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9765:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9766:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9767:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9768:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9769:       }
1.337     brouard  9770:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9771:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9772:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9773:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9774:       /* }      */
1.269     brouard  9775:       fprintf(ficresvpl,"******\n");
                   9776:       printf("******\n");
                   9777:       fprintf(ficlog,"******\n");
                   9778:       
                   9779:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9780:       oldm=oldms;savm=savms;
                   9781:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9782:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9783:       /*}*/
                   9784:     }
                   9785:     
                   9786:     fclose(ficresvpl);
1.288     brouard  9787:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9788:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9789: 
                   9790:  }
                   9791: /* Variance of back prevalence: varbprlim */
                   9792:  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){
                   9793:       /*------- Variance of back (stable) prevalence------*/
                   9794: 
                   9795:    char fileresvbl[FILENAMELENGTH];  
                   9796:    FILE  *ficresvbl;
                   9797: 
                   9798:    double **oldm, **savm;
                   9799:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9800:    int i1, k, nres, j ;
                   9801: 
                   9802:    strcpy(fileresvbl,"VBL_");
                   9803:    strcat(fileresvbl,fileresu);
                   9804:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9805:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9806:      exit(0);
                   9807:    }
                   9808:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9809:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9810:    
                   9811:    
                   9812:    i1=pow(2,cptcoveff);
                   9813:    if (cptcovn < 1){i1=1;}
                   9814:    
1.337     brouard  9815:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9816:      k=TKresult[nres];
1.338     brouard  9817:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9818:     /* for(k=1; k<=i1;k++){ */
                   9819:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9820:     /*          continue; */
1.269     brouard  9821:        fprintf(ficresvbl,"\n#****** ");
                   9822:        printf("\n#****** ");
                   9823:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9824:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  9825:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9826:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9827:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  9828:        /* for(j=1;j<=cptcoveff;j++) { */
                   9829:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9830:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9831:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9832:        /* } */
                   9833:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9834:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9835:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9836:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  9837:        }
                   9838:        fprintf(ficresvbl,"******\n");
                   9839:        printf("******\n");
                   9840:        fprintf(ficlog,"******\n");
                   9841:        
                   9842:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9843:        oldm=oldms;savm=savms;
                   9844:        
                   9845:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9846:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9847:        /*}*/
                   9848:      }
                   9849:    
                   9850:    fclose(ficresvbl);
                   9851:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9852:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9853: 
                   9854:  } /* End of varbprlim */
                   9855: 
1.126     brouard  9856: /************** Forecasting *****not tested NB*************/
1.227     brouard  9857: /* 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  9858:   
1.227     brouard  9859: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9860: /*   int *popage; */
                   9861: /*   double calagedatem, agelim, kk1, kk2; */
                   9862: /*   double *popeffectif,*popcount; */
                   9863: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9864: /*   /\* double ***mobaverage; *\/ */
                   9865: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9866: 
1.227     brouard  9867: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9868: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9869: /*   agelim=AGESUP; */
                   9870: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9871:   
1.227     brouard  9872: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9873:   
                   9874:   
1.227     brouard  9875: /*   strcpy(filerespop,"POP_");  */
                   9876: /*   strcat(filerespop,fileresu); */
                   9877: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9878: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9879: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9880: /*   } */
                   9881: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9882: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9883: 
1.227     brouard  9884: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9885: 
1.227     brouard  9886: /*   /\* if (mobilav!=0) { *\/ */
                   9887: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9888: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9889: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9890: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9891: /*   /\*   } *\/ */
                   9892: /*   /\* } *\/ */
1.126     brouard  9893: 
1.227     brouard  9894: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9895: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9896:   
1.227     brouard  9897: /*   agelim=AGESUP; */
1.126     brouard  9898:   
1.227     brouard  9899: /*   hstepm=1; */
                   9900: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9901:        
1.227     brouard  9902: /*   if (popforecast==1) { */
                   9903: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9904: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9905: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9906: /*     }  */
                   9907: /*     popage=ivector(0,AGESUP); */
                   9908: /*     popeffectif=vector(0,AGESUP); */
                   9909: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9910:     
1.227     brouard  9911: /*     i=1;    */
                   9912: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9913:     
1.227     brouard  9914: /*     imx=i; */
                   9915: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9916: /*   } */
1.218     brouard  9917:   
1.227     brouard  9918: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9919: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9920: /*       k=k+1; */
                   9921: /*       fprintf(ficrespop,"\n#******"); */
                   9922: /*       for(j=1;j<=cptcoveff;j++) { */
                   9923: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9924: /*       } */
                   9925: /*       fprintf(ficrespop,"******\n"); */
                   9926: /*       fprintf(ficrespop,"# Age"); */
                   9927: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9928: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9929:       
1.227     brouard  9930: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9931: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9932:        
1.227     brouard  9933: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9934: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9935: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9936:          
1.227     brouard  9937: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9938: /*       oldm=oldms;savm=savms; */
                   9939: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9940:          
1.227     brouard  9941: /*       for (h=0; h<=nhstepm; h++){ */
                   9942: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9943: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9944: /*         }  */
                   9945: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9946: /*           kk1=0.;kk2=0; */
                   9947: /*           for(i=1; i<=nlstate;i++) {               */
                   9948: /*             if (mobilav==1)  */
                   9949: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9950: /*             else { */
                   9951: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9952: /*             } */
                   9953: /*           } */
                   9954: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9955: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9956: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9957: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9958: /*           } */
                   9959: /*         } */
                   9960: /*         for(i=1; i<=nlstate;i++){ */
                   9961: /*           kk1=0.; */
                   9962: /*           for(j=1; j<=nlstate;j++){ */
                   9963: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9964: /*           } */
                   9965: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9966: /*         } */
1.218     brouard  9967:            
1.227     brouard  9968: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9969: /*           for(j=1; j<=nlstate;j++)  */
                   9970: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9971: /*       } */
                   9972: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9973: /*     } */
                   9974: /*       } */
1.218     brouard  9975:       
1.227     brouard  9976: /*       /\******\/ */
1.218     brouard  9977:       
1.227     brouard  9978: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9979: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9980: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9981: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9982: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9983:          
1.227     brouard  9984: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9985: /*       oldm=oldms;savm=savms; */
                   9986: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9987: /*       for (h=0; h<=nhstepm; h++){ */
                   9988: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9989: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9990: /*         }  */
                   9991: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9992: /*           kk1=0.;kk2=0; */
                   9993: /*           for(i=1; i<=nlstate;i++) {               */
                   9994: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9995: /*           } */
                   9996: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9997: /*         } */
                   9998: /*       } */
                   9999: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10000: /*     } */
                   10001: /*       } */
                   10002: /*     }  */
                   10003: /*   } */
1.218     brouard  10004:   
1.227     brouard  10005: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10006:   
1.227     brouard  10007: /*   if (popforecast==1) { */
                   10008: /*     free_ivector(popage,0,AGESUP); */
                   10009: /*     free_vector(popeffectif,0,AGESUP); */
                   10010: /*     free_vector(popcount,0,AGESUP); */
                   10011: /*   } */
                   10012: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10013: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10014: /*   fclose(ficrespop); */
                   10015: /* } /\* End of popforecast *\/ */
1.218     brouard  10016:  
1.126     brouard  10017: int fileappend(FILE *fichier, char *optionfich)
                   10018: {
                   10019:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10020:     printf("Problem with file: %s\n", optionfich);
                   10021:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10022:     return (0);
                   10023:   }
                   10024:   fflush(fichier);
                   10025:   return (1);
                   10026: }
                   10027: 
                   10028: 
                   10029: /**************** function prwizard **********************/
                   10030: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10031: {
                   10032: 
                   10033:   /* Wizard to print covariance matrix template */
                   10034: 
1.164     brouard  10035:   char ca[32], cb[32];
                   10036:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10037:   int numlinepar;
                   10038: 
                   10039:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10040:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10041:   for(i=1; i <=nlstate; i++){
                   10042:     jj=0;
                   10043:     for(j=1; j <=nlstate+ndeath; j++){
                   10044:       if(j==i) continue;
                   10045:       jj++;
                   10046:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10047:       printf("%1d%1d",i,j);
                   10048:       fprintf(ficparo,"%1d%1d",i,j);
                   10049:       for(k=1; k<=ncovmodel;k++){
                   10050:        /*        printf(" %lf",param[i][j][k]); */
                   10051:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10052:        printf(" 0.");
                   10053:        fprintf(ficparo," 0.");
                   10054:       }
                   10055:       printf("\n");
                   10056:       fprintf(ficparo,"\n");
                   10057:     }
                   10058:   }
                   10059:   printf("# Scales (for hessian or gradient estimation)\n");
                   10060:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10061:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10062:   for(i=1; i <=nlstate; i++){
                   10063:     jj=0;
                   10064:     for(j=1; j <=nlstate+ndeath; j++){
                   10065:       if(j==i) continue;
                   10066:       jj++;
                   10067:       fprintf(ficparo,"%1d%1d",i,j);
                   10068:       printf("%1d%1d",i,j);
                   10069:       fflush(stdout);
                   10070:       for(k=1; k<=ncovmodel;k++){
                   10071:        /*      printf(" %le",delti3[i][j][k]); */
                   10072:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10073:        printf(" 0.");
                   10074:        fprintf(ficparo," 0.");
                   10075:       }
                   10076:       numlinepar++;
                   10077:       printf("\n");
                   10078:       fprintf(ficparo,"\n");
                   10079:     }
                   10080:   }
                   10081:   printf("# Covariance matrix\n");
                   10082: /* # 121 Var(a12)\n\ */
                   10083: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10084: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10085: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10086: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10087: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10088: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10089: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10090:   fflush(stdout);
                   10091:   fprintf(ficparo,"# Covariance matrix\n");
                   10092:   /* # 121 Var(a12)\n\ */
                   10093:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10094:   /* #   ...\n\ */
                   10095:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10096:   
                   10097:   for(itimes=1;itimes<=2;itimes++){
                   10098:     jj=0;
                   10099:     for(i=1; i <=nlstate; i++){
                   10100:       for(j=1; j <=nlstate+ndeath; j++){
                   10101:        if(j==i) continue;
                   10102:        for(k=1; k<=ncovmodel;k++){
                   10103:          jj++;
                   10104:          ca[0]= k+'a'-1;ca[1]='\0';
                   10105:          if(itimes==1){
                   10106:            printf("#%1d%1d%d",i,j,k);
                   10107:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10108:          }else{
                   10109:            printf("%1d%1d%d",i,j,k);
                   10110:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10111:            /*  printf(" %.5le",matcov[i][j]); */
                   10112:          }
                   10113:          ll=0;
                   10114:          for(li=1;li <=nlstate; li++){
                   10115:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10116:              if(lj==li) continue;
                   10117:              for(lk=1;lk<=ncovmodel;lk++){
                   10118:                ll++;
                   10119:                if(ll<=jj){
                   10120:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10121:                  if(ll<jj){
                   10122:                    if(itimes==1){
                   10123:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10124:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10125:                    }else{
                   10126:                      printf(" 0.");
                   10127:                      fprintf(ficparo," 0.");
                   10128:                    }
                   10129:                  }else{
                   10130:                    if(itimes==1){
                   10131:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10132:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10133:                    }else{
                   10134:                      printf(" 0.");
                   10135:                      fprintf(ficparo," 0.");
                   10136:                    }
                   10137:                  }
                   10138:                }
                   10139:              } /* end lk */
                   10140:            } /* end lj */
                   10141:          } /* end li */
                   10142:          printf("\n");
                   10143:          fprintf(ficparo,"\n");
                   10144:          numlinepar++;
                   10145:        } /* end k*/
                   10146:       } /*end j */
                   10147:     } /* end i */
                   10148:   } /* end itimes */
                   10149: 
                   10150: } /* end of prwizard */
                   10151: /******************* Gompertz Likelihood ******************************/
                   10152: double gompertz(double x[])
                   10153: { 
1.302     brouard  10154:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10155:   int i,n=0; /* n is the size of the sample */
                   10156: 
1.220     brouard  10157:   for (i=1;i<=imx ; i++) {
1.126     brouard  10158:     sump=sump+weight[i];
                   10159:     /*    sump=sump+1;*/
                   10160:     num=num+1;
                   10161:   }
1.302     brouard  10162:   L=0.0;
                   10163:   /* agegomp=AGEGOMP; */
1.126     brouard  10164:   /* for (i=0; i<=imx; i++) 
                   10165:      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]);*/
                   10166: 
1.302     brouard  10167:   for (i=1;i<=imx ; i++) {
                   10168:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10169:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10170:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10171:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10172:      * +
                   10173:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10174:      */
                   10175:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10176:        if (cens[i] == 1){
                   10177:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10178:        } else if (cens[i] == 0){
1.126     brouard  10179:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10180:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10181:       } else
                   10182:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10183:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10184:        L=L+A*weight[i];
1.126     brouard  10185:        /*      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  10186:      }
                   10187:   }
1.126     brouard  10188: 
1.302     brouard  10189:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10190:  
                   10191:   return -2*L*num/sump;
                   10192: }
                   10193: 
1.136     brouard  10194: #ifdef GSL
                   10195: /******************* Gompertz_f Likelihood ******************************/
                   10196: double gompertz_f(const gsl_vector *v, void *params)
                   10197: { 
1.302     brouard  10198:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10199:   double *x= (double *) v->data;
                   10200:   int i,n=0; /* n is the size of the sample */
                   10201: 
                   10202:   for (i=0;i<=imx-1 ; i++) {
                   10203:     sump=sump+weight[i];
                   10204:     /*    sump=sump+1;*/
                   10205:     num=num+1;
                   10206:   }
                   10207:  
                   10208:  
                   10209:   /* for (i=0; i<=imx; i++) 
                   10210:      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]);*/
                   10211:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10212:   for (i=1;i<=imx ; i++)
                   10213:     {
                   10214:       if (cens[i] == 1 && wav[i]>1)
                   10215:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10216:       
                   10217:       if (cens[i] == 0 && wav[i]>1)
                   10218:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10219:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10220:       
                   10221:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10222:       if (wav[i] > 1 ) { /* ??? */
                   10223:        LL=LL+A*weight[i];
                   10224:        /*      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]);*/
                   10225:       }
                   10226:     }
                   10227: 
                   10228:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10229:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10230:  
                   10231:   return -2*LL*num/sump;
                   10232: }
                   10233: #endif
                   10234: 
1.126     brouard  10235: /******************* Printing html file ***********/
1.201     brouard  10236: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10237:                  int lastpass, int stepm, int weightopt, char model[],\
                   10238:                  int imx,  double p[],double **matcov,double agemortsup){
                   10239:   int i,k;
                   10240: 
                   10241:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10242:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10243:   for (i=1;i<=2;i++) 
                   10244:     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  10245:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10246:   fprintf(fichtm,"</ul>");
                   10247: 
                   10248: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10249: 
                   10250:  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>");
                   10251: 
                   10252:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10253:    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]);
                   10254: 
                   10255:  
                   10256:   fflush(fichtm);
                   10257: }
                   10258: 
                   10259: /******************* Gnuplot file **************/
1.201     brouard  10260: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10261: 
                   10262:   char dirfileres[132],optfileres[132];
1.164     brouard  10263: 
1.126     brouard  10264:   int ng;
                   10265: 
                   10266: 
                   10267:   /*#ifdef windows */
                   10268:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10269:     /*#endif */
                   10270: 
                   10271: 
                   10272:   strcpy(dirfileres,optionfilefiname);
                   10273:   strcpy(optfileres,"vpl");
1.199     brouard  10274:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10275:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10276:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10277:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10278:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10279: 
                   10280: } 
                   10281: 
1.136     brouard  10282: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10283: {
1.126     brouard  10284: 
1.136     brouard  10285:   /*-------- data file ----------*/
                   10286:   FILE *fic;
                   10287:   char dummy[]="                         ";
1.240     brouard  10288:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10289:   int lstra;
1.136     brouard  10290:   int linei, month, year,iout;
1.302     brouard  10291:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10292:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10293:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10294:   char *stratrunc;
1.223     brouard  10295: 
1.240     brouard  10296:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10297:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10298:   for(v=1;v<NCOVMAX;v++){
                   10299:     DummyV[v]=0;
                   10300:     FixedV[v]=0;
                   10301:   }
1.126     brouard  10302: 
1.240     brouard  10303:   for(v=1; v <=ncovcol;v++){
                   10304:     DummyV[v]=0;
                   10305:     FixedV[v]=0;
                   10306:   }
                   10307:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10308:     DummyV[v]=1;
                   10309:     FixedV[v]=0;
                   10310:   }
                   10311:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10312:     DummyV[v]=0;
                   10313:     FixedV[v]=1;
                   10314:   }
                   10315:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10316:     DummyV[v]=1;
                   10317:     FixedV[v]=1;
                   10318:   }
                   10319:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10320:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10321:     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]);
                   10322:   }
1.339     brouard  10323:   
                   10324:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10325:   
1.136     brouard  10326:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10327:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10328:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10329:   }
1.126     brouard  10330: 
1.302     brouard  10331:     /* Is it a BOM UTF-8 Windows file? */
                   10332:   /* First data line */
                   10333:   linei=0;
                   10334:   while(fgets(line, MAXLINE, fic)) {
                   10335:     noffset=0;
                   10336:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10337:     {
                   10338:       noffset=noffset+3;
                   10339:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10340:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10341:       fflush(ficlog); return 1;
                   10342:     }
                   10343:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10344:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10345:     {
                   10346:       noffset=noffset+2;
1.304     brouard  10347:       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);
                   10348:       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  10349:       fflush(ficlog); return 1;
                   10350:     }
                   10351:     else if( line[0] == 0 && line[1] == 0)
                   10352:     {
                   10353:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10354:        noffset=noffset+4;
1.304     brouard  10355:        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);
                   10356:        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  10357:        fflush(ficlog); return 1;
                   10358:       }
                   10359:     } else{
                   10360:       ;/*printf(" Not a BOM file\n");*/
                   10361:     }
                   10362:         /* If line starts with a # it is a comment */
                   10363:     if (line[noffset] == '#') {
                   10364:       linei=linei+1;
                   10365:       break;
                   10366:     }else{
                   10367:       break;
                   10368:     }
                   10369:   }
                   10370:   fclose(fic);
                   10371:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10372:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10373:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10374:   }
                   10375:   /* Not a Bom file */
                   10376:   
1.136     brouard  10377:   i=1;
                   10378:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10379:     linei=linei+1;
                   10380:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10381:       if(line[j] == '\t')
                   10382:        line[j] = ' ';
                   10383:     }
                   10384:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10385:       ;
                   10386:     };
                   10387:     line[j+1]=0;  /* Trims blanks at end of line */
                   10388:     if(line[0]=='#'){
                   10389:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10390:       printf("Comment line\n%s\n",line);
                   10391:       continue;
                   10392:     }
                   10393:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10394:     strcpy(line, linetmp);
1.223     brouard  10395:     
                   10396:     /* Loops on waves */
                   10397:     for (j=maxwav;j>=1;j--){
                   10398:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10399:        cutv(stra, strb, line, ' '); 
                   10400:        if(strb[0]=='.') { /* Missing value */
                   10401:          lval=-1;
                   10402:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10403:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10404:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10405:            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);
                   10406:            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);
                   10407:            return 1;
                   10408:          }
                   10409:        }else{
                   10410:          errno=0;
                   10411:          /* what_kind_of_number(strb); */
                   10412:          dval=strtod(strb,&endptr); 
                   10413:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10414:          /* if(strb != endptr && *endptr == '\0') */
                   10415:          /*    dval=dlval; */
                   10416:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10417:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10418:            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);
                   10419:            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);
                   10420:            return 1;
                   10421:          }
                   10422:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10423:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10424:        }
                   10425:        strcpy(line,stra);
1.223     brouard  10426:       }/* end loop ntqv */
1.225     brouard  10427:       
1.223     brouard  10428:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10429:        cutv(stra, strb, line, ' '); 
                   10430:        if(strb[0]=='.') { /* Missing value */
                   10431:          lval=-1;
                   10432:        }else{
                   10433:          errno=0;
                   10434:          lval=strtol(strb,&endptr,10); 
                   10435:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10436:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10437:            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);
                   10438:            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);
                   10439:            return 1;
                   10440:          }
                   10441:        }
                   10442:        if(lval <-1 || lval >1){
                   10443:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10444:  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  10445:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10446:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10447:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10448:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10449:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10450:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10451:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10452:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10453:  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  10454:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10455:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10456:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10457:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10458:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10459:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10460:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10461:          return 1;
                   10462:        }
1.341     brouard  10463:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10464:        strcpy(line,stra);
1.223     brouard  10465:       }/* end loop ntv */
1.225     brouard  10466:       
1.223     brouard  10467:       /* Statuses  at wave */
1.137     brouard  10468:       cutv(stra, strb, line, ' '); 
1.223     brouard  10469:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10470:        lval=-1;
1.136     brouard  10471:       }else{
1.238     brouard  10472:        errno=0;
                   10473:        lval=strtol(strb,&endptr,10); 
                   10474:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10475:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10476:          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);
                   10477:          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);
                   10478:          return 1;
                   10479:        }
1.136     brouard  10480:       }
1.225     brouard  10481:       
1.136     brouard  10482:       s[j][i]=lval;
1.225     brouard  10483:       
1.223     brouard  10484:       /* Date of Interview */
1.136     brouard  10485:       strcpy(line,stra);
                   10486:       cutv(stra, strb,line,' ');
1.169     brouard  10487:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10488:       }
1.169     brouard  10489:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10490:        month=99;
                   10491:        year=9999;
1.136     brouard  10492:       }else{
1.225     brouard  10493:        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);
                   10494:        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);
                   10495:        return 1;
1.136     brouard  10496:       }
                   10497:       anint[j][i]= (double) year; 
1.302     brouard  10498:       mint[j][i]= (double)month;
                   10499:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10500:       /*       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]); */
                   10501:       /*       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]); */
                   10502:       /* } */
1.136     brouard  10503:       strcpy(line,stra);
1.223     brouard  10504:     } /* End loop on waves */
1.225     brouard  10505:     
1.223     brouard  10506:     /* Date of death */
1.136     brouard  10507:     cutv(stra, strb,line,' '); 
1.169     brouard  10508:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10509:     }
1.169     brouard  10510:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10511:       month=99;
                   10512:       year=9999;
                   10513:     }else{
1.141     brouard  10514:       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  10515:       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);
                   10516:       return 1;
1.136     brouard  10517:     }
                   10518:     andc[i]=(double) year; 
                   10519:     moisdc[i]=(double) month; 
                   10520:     strcpy(line,stra);
                   10521:     
1.223     brouard  10522:     /* Date of birth */
1.136     brouard  10523:     cutv(stra, strb,line,' '); 
1.169     brouard  10524:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10525:     }
1.169     brouard  10526:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10527:       month=99;
                   10528:       year=9999;
                   10529:     }else{
1.141     brouard  10530:       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);
                   10531:       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  10532:       return 1;
1.136     brouard  10533:     }
                   10534:     if (year==9999) {
1.141     brouard  10535:       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);
                   10536:       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  10537:       return 1;
                   10538:       
1.136     brouard  10539:     }
                   10540:     annais[i]=(double)(year);
1.302     brouard  10541:     moisnais[i]=(double)(month);
                   10542:     for (j=1;j<=maxwav;j++){
                   10543:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10544:        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]);
                   10545:        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]);
                   10546:       }
                   10547:     }
                   10548: 
1.136     brouard  10549:     strcpy(line,stra);
1.225     brouard  10550:     
1.223     brouard  10551:     /* Sample weight */
1.136     brouard  10552:     cutv(stra, strb,line,' '); 
                   10553:     errno=0;
                   10554:     dval=strtod(strb,&endptr); 
                   10555:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10556:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10557:       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  10558:       fflush(ficlog);
                   10559:       return 1;
                   10560:     }
                   10561:     weight[i]=dval; 
                   10562:     strcpy(line,stra);
1.225     brouard  10563:     
1.223     brouard  10564:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10565:       cutv(stra, strb, line, ' '); 
                   10566:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10567:        lval=-1;
1.311     brouard  10568:        coqvar[iv][i]=NAN; 
                   10569:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10570:       }else{
1.225     brouard  10571:        errno=0;
                   10572:        /* what_kind_of_number(strb); */
                   10573:        dval=strtod(strb,&endptr);
                   10574:        /* if(strb != endptr && *endptr == '\0') */
                   10575:        /*   dval=dlval; */
                   10576:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10577:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10578:          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);
                   10579:          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);
                   10580:          return 1;
                   10581:        }
                   10582:        coqvar[iv][i]=dval; 
1.226     brouard  10583:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10584:       }
                   10585:       strcpy(line,stra);
                   10586:     }/* end loop nqv */
1.136     brouard  10587:     
1.223     brouard  10588:     /* Covariate values */
1.136     brouard  10589:     for (j=ncovcol;j>=1;j--){
                   10590:       cutv(stra, strb,line,' '); 
1.223     brouard  10591:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10592:        lval=-1;
1.136     brouard  10593:       }else{
1.225     brouard  10594:        errno=0;
                   10595:        lval=strtol(strb,&endptr,10); 
                   10596:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10597:          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);
                   10598:          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);
                   10599:          return 1;
                   10600:        }
1.136     brouard  10601:       }
                   10602:       if(lval <-1 || lval >1){
1.225     brouard  10603:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10604:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10605:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10606:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10607:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10608:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10609:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10610:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10611:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10612:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10613:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10614:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10615:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10616:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10617:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10618:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10619:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10620:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10621:        return 1;
1.136     brouard  10622:       }
                   10623:       covar[j][i]=(double)(lval);
                   10624:       strcpy(line,stra);
                   10625:     }  
                   10626:     lstra=strlen(stra);
1.225     brouard  10627:     
1.136     brouard  10628:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10629:       stratrunc = &(stra[lstra-9]);
                   10630:       num[i]=atol(stratrunc);
                   10631:     }
                   10632:     else
                   10633:       num[i]=atol(stra);
                   10634:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10635:       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;}*/
                   10636:     
                   10637:     i=i+1;
                   10638:   } /* End loop reading  data */
1.225     brouard  10639:   
1.136     brouard  10640:   *imax=i-1; /* Number of individuals */
                   10641:   fclose(fic);
1.225     brouard  10642:   
1.136     brouard  10643:   return (0);
1.164     brouard  10644:   /* endread: */
1.225     brouard  10645:   printf("Exiting readdata: ");
                   10646:   fclose(fic);
                   10647:   return (1);
1.223     brouard  10648: }
1.126     brouard  10649: 
1.234     brouard  10650: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10651:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10652:   while (*p2 == ' ')
1.234     brouard  10653:     p2++; 
                   10654:   /* while ((*p1++ = *p2++) !=0) */
                   10655:   /*   ; */
                   10656:   /* do */
                   10657:   /*   while (*p2 == ' ') */
                   10658:   /*     p2++; */
                   10659:   /* while (*p1++ == *p2++); */
                   10660:   *stri=p2; 
1.145     brouard  10661: }
                   10662: 
1.330     brouard  10663: int decoderesult( char resultline[], int nres)
1.230     brouard  10664: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10665: {
1.235     brouard  10666:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10667:   char resultsav[MAXLINE];
1.330     brouard  10668:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10669:   /* int modelresult[MAXLINE]; */
1.230     brouard  10670:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10671: 
1.234     brouard  10672:   removefirstspace(&resultline);
1.332     brouard  10673:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10674: 
1.332     brouard  10675:   strcpy(resultsav,resultline);
1.342   ! brouard  10676:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  10677:   if (strlen(resultsav) >1){
1.334     brouard  10678:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10679:   }
1.253     brouard  10680:   if(j == 0){ /* Resultline but no = */
                   10681:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10682:     return (0);
                   10683:   }
1.234     brouard  10684:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10685:     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);
                   10686:     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  10687:     /* return 1;*/
1.234     brouard  10688:   }
1.334     brouard  10689:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10690:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10691:       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  10692:       /* 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  10693:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10694:       /* If a blank, then strc="V4=" and strd='\0' */
                   10695:       if(strc[0]=='\0'){
                   10696:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10697:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10698:        return 1;
                   10699:       }
1.234     brouard  10700:     }else
                   10701:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10702:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10703:     
1.230     brouard  10704:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10705:     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  10706:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10707:     /* cptcovsel++;     */
                   10708:     if (nbocc(stra,'=') >0)
                   10709:       strcpy(resultsav,stra); /* and analyzes it */
                   10710:   }
1.235     brouard  10711:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10712:   /* 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  10713:   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  10714:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10715:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10716:       match=0;
1.318     brouard  10717:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10718:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10719:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10720:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10721:          break;
                   10722:        }
                   10723:       }
                   10724:       if(match == 0){
1.338     brouard  10725:        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]);
                   10726:        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  10727:        return 1;
1.234     brouard  10728:       }
1.332     brouard  10729:     }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*/
                   10730:       /* We feed resultmodel[k1]=k2; */
                   10731:       match=0;
                   10732:       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 */
                   10733:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10734:          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  10735:          resultmodel[nres][k1]=k2; /* Added here */
1.342   ! brouard  10736:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  10737:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10738:          break;
                   10739:        }
                   10740:       }
                   10741:       if(match == 0){
1.338     brouard  10742:        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]);
                   10743:        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  10744:       return 1;
                   10745:       }
                   10746:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10747:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10748:       match=0;
1.342   ! brouard  10749:       /* 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  10750:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10751:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10752:          /* modelresult[k2]=k1; */
1.342   ! brouard  10753:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  10754:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10755:        }
                   10756:       }
                   10757:       if(match == 0){
1.338     brouard  10758:        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);
                   10759:        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  10760:        return 1;
                   10761:       }
                   10762:       match=0;
                   10763:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10764:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10765:          /* modelresult[k2]=k1;*/
1.342   ! brouard  10766:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  10767:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10768:          break;
                   10769:        }
                   10770:       }
                   10771:       if(match == 0){
1.338     brouard  10772:        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);
                   10773:        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  10774:        return 1;
                   10775:       }
                   10776:     }/* End of testing */
1.333     brouard  10777:   }/* End loop cptcovt */
1.235     brouard  10778:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10779:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10780:   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)
                   10781:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10782:     match=0;
1.318     brouard  10783:     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  10784:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10785:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10786:          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  10787:          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  10788:          ++match;
                   10789:        }
                   10790:       }
                   10791:     }
                   10792:     if(match == 0){
1.338     brouard  10793:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10794:       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  10795:       return 1;
1.234     brouard  10796:     }else if(match > 1){
1.338     brouard  10797:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10798:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10799:       return 1;
1.234     brouard  10800:     }
                   10801:   }
1.334     brouard  10802:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10803:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10804:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10805:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10806:   /* 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*/
                   10807:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10808:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10809:   /*    1 0 0 0 */
                   10810:   /*    2 1 0 0 */
                   10811:   /*    3 0 1 0 */ 
1.330     brouard  10812:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10813:   /*    5 0 0 1 */
1.330     brouard  10814:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10815:   /*    7 0 1 1 */
                   10816:   /*    8 1 1 1 */
1.237     brouard  10817:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10818:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10819:   /* V5*age V5 known which value for nres?  */
                   10820:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10821:   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.
                   10822:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10823:     /* k counting number of combination of single dummies in the equation model */
                   10824:     /* k4 counting single dummies in the equation model */
                   10825:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10826:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10827:        /* 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  10828:       /* 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  10829:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10830:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10831:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10832:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10833:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10834:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10835:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10836:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10837:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10838:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10839:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10840:       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  10841:       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  10842:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10843:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10844:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10845:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10846:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10847:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10848:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10849:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342   ! brouard  10850:       /* 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  10851:       k4++;;
1.331     brouard  10852:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10853:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10854:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10855:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10856:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10857:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10858:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10859:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10860:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10861:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10862:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10863:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10864:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10865:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10866:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10867:       precov[nres][k1]=Tvalsel[k3q];
1.342   ! brouard  10868:       /* 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  10869:       k4q++;;
1.331     brouard  10870:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10871:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10872:       /* Wrong we want the value of variable name Tvar[k1] */
                   10873:       
                   10874:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10875:       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  10876:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10877:       precov[nres][k1]=Tvalsel[k3];
1.342   ! brouard  10878:       /* 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  10879:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10880:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10881:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10882:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10883:       precov[nres][k1]=Tvalsel[k3q];
1.342   ! brouard  10884:       /* 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  10885:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10886:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342   ! brouard  10887:       /* 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  10888:     }else{
1.332     brouard  10889:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10890:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10891:     }
                   10892:   }
1.234     brouard  10893:   
1.334     brouard  10894:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10895:   return (0);
                   10896: }
1.235     brouard  10897: 
1.230     brouard  10898: int decodemodel( char model[], int lastobs)
                   10899:  /**< This routine decodes the model and returns:
1.224     brouard  10900:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10901:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10902:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10903:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10904:        * - cptcovage number of covariates with age*products =2
                   10905:        * - cptcovs number of simple covariates
1.339     brouard  10906:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  10907:        * - 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  10908:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  10909:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10910:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10911:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10912:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10913:        */
1.319     brouard  10914: /* 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  10915: {
1.238     brouard  10916:   int i, j, k, ks, v;
1.227     brouard  10917:   int  j1, k1, k2, k3, k4;
1.136     brouard  10918:   char modelsav[80];
1.145     brouard  10919:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10920:   char *strpt;
1.136     brouard  10921: 
1.145     brouard  10922:   /*removespace(model);*/
1.136     brouard  10923:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10924:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10925:     if (strstr(model,"AGE") !=0){
1.192     brouard  10926:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10927:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10928:       return 1;
                   10929:     }
1.141     brouard  10930:     if (strstr(model,"v") !=0){
1.338     brouard  10931:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   10932:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  10933:       return 1;
                   10934:     }
1.187     brouard  10935:     strcpy(modelsav,model); 
                   10936:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  10937:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  10938:       if(strpt != model){
1.338     brouard  10939:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10940:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10941:  corresponding column of parameters.\n",model);
1.338     brouard  10942:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10943:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10944:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10945:        return 1;
1.225     brouard  10946:       }
1.187     brouard  10947:       nagesqr=1;
                   10948:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10949:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10950:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10951:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10952:       else 
1.234     brouard  10953:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10954:     }else
                   10955:       nagesqr=0;
                   10956:     if (strlen(modelsav) >1){
                   10957:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10958:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10959:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10960:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10961:                     * cst, age and age*age 
                   10962:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10963:       /* including age products which are counted in cptcovage.
                   10964:        * but the covariates which are products must be treated 
                   10965:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10966:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10967:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10968:       
                   10969:       
1.187     brouard  10970:       /*   Design
                   10971:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10972:        *  <          ncovcol=8                >
                   10973:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10974:        *   k=  1    2      3       4     5       6      7        8
                   10975:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10976:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10977:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10978:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10979:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10980:        *  Tage[++cptcovage]=k
                   10981:        *       if products, new covar are created after ncovcol with k1
                   10982:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10983:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10984:        *  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
                   10985:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10986:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10987:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10988:        *  <          ncovcol=8                >
                   10989:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10990:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10991:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10992:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10993:        * p Tprod[1]@2={                         6, 5}
                   10994:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10995:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10996:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10997:        *How to reorganize? Tvars(orted)
1.187     brouard  10998:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10999:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11000:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11001:        * Struct []
                   11002:        */
1.225     brouard  11003:       
1.187     brouard  11004:       /* This loop fills the array Tvar from the string 'model'.*/
                   11005:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11006:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11007:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11008:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11009:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11010:       /*       k=1 Tvar[1]=2 (from V2) */
                   11011:       /*       k=5 Tvar[5] */
                   11012:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11013:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11014:       /*       } */
1.198     brouard  11015:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11016:       /*
                   11017:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11018:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11019:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11020:       }
1.187     brouard  11021:       cptcovage=0;
1.319     brouard  11022:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11023:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11024:                                         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" */
                   11025:        if (nbocc(modelsav,'+')==0)
                   11026:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11027:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11028:        /*scanf("%d",i);*/
1.319     brouard  11029:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   11030:          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  11031:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   11032:            /* covar is not filled and then is empty */
                   11033:            cptcovprod--;
                   11034:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  11035:            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  11036:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  11037:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11038:            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  11039:            /*printf("stre=%s ", stre);*/
                   11040:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   11041:            cptcovprod--;
                   11042:            cutl(stre,strb,strc,'V');
                   11043:            Tvar[k]=atoi(stre);
                   11044:            Typevar[k]=1;  /* 1 for age product */
                   11045:            cptcovage++;
                   11046:            Tage[cptcovage]=k;
                   11047:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11048:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11049:            cptcovn++;
                   11050:            cptcovprodnoage++;k1++;
                   11051:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11052:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11053:                                                because this model-covariate is a construction we invent a new column
                   11054:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11055:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11056:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11057:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11058:            /* Please remark that the new variables are model dependent */
                   11059:            /* If we have 4 variable but the model uses only 3, like in
                   11060:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11061:             *  k=     1     2       3   4     5        6        7       8
                   11062:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11063:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11064:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11065:             */
1.339     brouard  11066:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11067:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11068:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11069:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11070:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11071:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11072:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11073:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11074:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11075:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11076:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11077:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11078:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11079:            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 */
                   11080:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11081:              /* Computes the new covariate which is a product of
                   11082:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11083:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11084:              }
                   11085:            } /*End of FixedV */
1.234     brouard  11086:          } /* End age is not in the model */
                   11087:        } /* End if model includes a product */
1.319     brouard  11088:        else { /* not a product */
1.234     brouard  11089:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11090:          /*  scanf("%d",i);*/
                   11091:          cutl(strd,strc,strb,'V');
                   11092:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11093:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11094:          Tvar[k]=atoi(strd);
                   11095:          Typevar[k]=0;  /* 0 for simple covariates */
                   11096:        }
                   11097:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11098:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11099:                                  scanf("%d",i);*/
1.187     brouard  11100:       } /* end of loop + on total covariates */
                   11101:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11102:   } /* end if strlen(model == 0) */
1.136     brouard  11103:   
                   11104:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11105:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11106:   
1.136     brouard  11107:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11108:      printf("cptcovprod=%d ", cptcovprod);
                   11109:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11110:      scanf("%d ",i);*/
                   11111: 
                   11112: 
1.230     brouard  11113: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11114:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11115: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11116:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11117:    k =           1    2   3     4       5       6      7      8        9
                   11118:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11119:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11120:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11121:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11122:          Tmodelind[combination of covar]=k;
1.225     brouard  11123: */  
                   11124: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11125:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11126:   /* 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  11127:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11128:   printf("Model=1+age+%s\n\
1.227     brouard  11129: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11130: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11131: 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  11132:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11133: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11134: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11135: 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  11136:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
        !          11137:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.339     brouard  11138:   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 */
1.234     brouard  11139:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11140:       Fixed[k]= 0;
                   11141:       Dummy[k]= 0;
1.225     brouard  11142:       ncoveff++;
1.232     brouard  11143:       ncovf++;
1.234     brouard  11144:       nsd++;
                   11145:       modell[k].maintype= FTYPE;
                   11146:       TvarsD[nsd]=Tvar[k];
                   11147:       TvarsDind[nsd]=k;
1.330     brouard  11148:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11149:       TvarF[ncovf]=Tvar[k];
                   11150:       TvarFind[ncovf]=k;
                   11151:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11152:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11153:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11154:     }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  11155:       Fixed[k]= 0;
                   11156:       Dummy[k]= 0;
                   11157:       ncoveff++;
                   11158:       ncovf++;
                   11159:       modell[k].maintype= FTYPE;
                   11160:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11161:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11162:       TvarFind[ncovf]=k;
1.230     brouard  11163:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11164:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11165:     }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  11166:       Fixed[k]= 0;
                   11167:       Dummy[k]= 1;
1.230     brouard  11168:       nqfveff++;
1.234     brouard  11169:       modell[k].maintype= FTYPE;
                   11170:       modell[k].subtype= FQ;
                   11171:       nsq++;
1.334     brouard  11172:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11173:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11174:       ncovf++;
1.234     brouard  11175:       TvarF[ncovf]=Tvar[k];
                   11176:       TvarFind[ncovf]=k;
1.231     brouard  11177:       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  11178:       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  11179:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11180:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11181:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11182:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11183:       ncovvt++;
                   11184:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11185:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11186: 
1.227     brouard  11187:       Fixed[k]= 1;
                   11188:       Dummy[k]= 0;
1.225     brouard  11189:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11190:       modell[k].maintype= VTYPE;
                   11191:       modell[k].subtype= VD;
                   11192:       nsd++;
                   11193:       TvarsD[nsd]=Tvar[k];
                   11194:       TvarsDind[nsd]=k;
1.330     brouard  11195:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11196:       ncovv++; /* Only simple time varying variables */
                   11197:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11198:       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  11199:       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 */
                   11200:       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  11201:       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);
                   11202:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11203:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11204:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11205:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11206:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11207:       ncovvt++;
                   11208:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11209:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11210:       
1.234     brouard  11211:       Fixed[k]= 1;
                   11212:       Dummy[k]= 1;
                   11213:       nqtveff++;
                   11214:       modell[k].maintype= VTYPE;
                   11215:       modell[k].subtype= VQ;
                   11216:       ncovv++; /* Only simple time varying variables */
                   11217:       nsq++;
1.334     brouard  11218:       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) */
                   11219:       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  11220:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11221:       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  11222:       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 */
                   11223:       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  11224:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11225:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.342   ! brouard  11226:       /* 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); */
        !          11227:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11228:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11229:       ncova++;
                   11230:       TvarA[ncova]=Tvar[k];
                   11231:       TvarAind[ncova]=k;
1.231     brouard  11232:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11233:        Fixed[k]= 2;
                   11234:        Dummy[k]= 2;
                   11235:        modell[k].maintype= ATYPE;
                   11236:        modell[k].subtype= APFD;
                   11237:        /* ncoveff++; */
1.227     brouard  11238:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11239:        Fixed[k]= 2;
                   11240:        Dummy[k]= 3;
                   11241:        modell[k].maintype= ATYPE;
                   11242:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11243:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11244:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11245:        Fixed[k]= 3;
                   11246:        Dummy[k]= 2;
                   11247:        modell[k].maintype= ATYPE;
                   11248:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11249:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11250:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11251:        Fixed[k]= 3;
                   11252:        Dummy[k]= 3;
                   11253:        modell[k].maintype= ATYPE;
                   11254:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11255:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11256:       }
1.339     brouard  11257:     }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  */
                   11258:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11259:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11260:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11261:       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 */
                   11262:       ncovvt++;
                   11263:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11264:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11265:       ncovvt++;
                   11266:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11267:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11268: 
                   11269: 
                   11270:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11271:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11272:          Fixed[k]= 1;
                   11273:          Dummy[k]= 0;
                   11274:          modell[k].maintype= FTYPE;
                   11275:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11276:          ncovf++; /* Fixed variables without age */
                   11277:          TvarF[ncovf]=Tvar[k];
                   11278:          TvarFind[ncovf]=k;
1.339     brouard  11279:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11280:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11281:          Dummy[k]= 1;
                   11282:          modell[k].maintype= FTYPE;
                   11283:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11284:          ncovf++; /* Varying variables without age */
                   11285:          TvarF[ncovf]=Tvar[k];
                   11286:          TvarFind[ncovf]=k;
1.339     brouard  11287:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11288:          Fixed[k]= 1;
                   11289:          Dummy[k]= 0;
                   11290:          modell[k].maintype= VTYPE;
                   11291:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11292:          ncovv++; /* Varying variables without age */
1.339     brouard  11293:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11294:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11295:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11296:          Fixed[k]= 1;
                   11297:          Dummy[k]= 1;
                   11298:          modell[k].maintype= VTYPE;
                   11299:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11300:          ncovv++; /* Varying variables without age */
                   11301:          TvarV[ncovv]=Tvar[k];
                   11302:          TvarVind[ncovv]=k;
                   11303:        }
1.339     brouard  11304:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11305:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11306:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11307:          Dummy[k]= 1;
                   11308:          modell[k].maintype= FTYPE;
                   11309:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11310:          ncovf++; /* Fixed variables without age */
                   11311:          TvarF[ncovf]=Tvar[k];
                   11312:          TvarFind[ncovf]=k;
1.339     brouard  11313:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11314:          Fixed[k]= 1;
                   11315:          Dummy[k]= 1;
                   11316:          modell[k].maintype= VTYPE;
                   11317:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11318:          ncovv++; /* Varying variables without age */
                   11319:          TvarV[ncovv]=Tvar[k];
                   11320:          TvarVind[ncovv]=k;
1.339     brouard  11321:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11322:          Fixed[k]= 1;
                   11323:          Dummy[k]= 1;
                   11324:          modell[k].maintype= VTYPE;
                   11325:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11326:          ncovv++; /* Varying variables without age */
                   11327:          TvarV[ncovv]=Tvar[k];
                   11328:          TvarVind[ncovv]=k;
                   11329:          ncovv++; /* Varying variables without age */
                   11330:          TvarV[ncovv]=Tvar[k];
                   11331:          TvarVind[ncovv]=k;
                   11332:        }
1.339     brouard  11333:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11334:        if(Tvard[k1][2] <=ncovcol){
                   11335:          Fixed[k]= 1;
                   11336:          Dummy[k]= 1;
                   11337:          modell[k].maintype= VTYPE;
                   11338:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11339:          ncovv++; /* Varying variables without age */
                   11340:          TvarV[ncovv]=Tvar[k];
                   11341:          TvarVind[ncovv]=k;
                   11342:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11343:          Fixed[k]= 1;
                   11344:          Dummy[k]= 1;
                   11345:          modell[k].maintype= VTYPE;
                   11346:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11347:          ncovv++; /* Varying variables without age */
                   11348:          TvarV[ncovv]=Tvar[k];
                   11349:          TvarVind[ncovv]=k;
                   11350:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11351:          Fixed[k]= 1;
                   11352:          Dummy[k]= 0;
                   11353:          modell[k].maintype= VTYPE;
                   11354:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11355:          ncovv++; /* Varying variables without age */
                   11356:          TvarV[ncovv]=Tvar[k];
                   11357:          TvarVind[ncovv]=k;
                   11358:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11359:          Fixed[k]= 1;
                   11360:          Dummy[k]= 1;
                   11361:          modell[k].maintype= VTYPE;
                   11362:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11363:          ncovv++; /* Varying variables without age */
                   11364:          TvarV[ncovv]=Tvar[k];
                   11365:          TvarVind[ncovv]=k;
                   11366:        }
1.339     brouard  11367:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11368:        if(Tvard[k1][2] <=ncovcol){
                   11369:          Fixed[k]= 1;
                   11370:          Dummy[k]= 1;
                   11371:          modell[k].maintype= VTYPE;
                   11372:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11373:          ncovv++; /* Varying variables without age */
                   11374:          TvarV[ncovv]=Tvar[k];
                   11375:          TvarVind[ncovv]=k;
                   11376:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11377:          Fixed[k]= 1;
                   11378:          Dummy[k]= 1;
                   11379:          modell[k].maintype= VTYPE;
                   11380:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11381:          ncovv++; /* Varying variables without age */
                   11382:          TvarV[ncovv]=Tvar[k];
                   11383:          TvarVind[ncovv]=k;
                   11384:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11385:          Fixed[k]= 1;
                   11386:          Dummy[k]= 1;
                   11387:          modell[k].maintype= VTYPE;
                   11388:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11389:          ncovv++; /* Varying variables without age */
                   11390:          TvarV[ncovv]=Tvar[k];
                   11391:          TvarVind[ncovv]=k;
                   11392:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11393:          Fixed[k]= 1;
                   11394:          Dummy[k]= 1;
                   11395:          modell[k].maintype= VTYPE;
                   11396:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11397:          ncovv++; /* Varying variables without age */
                   11398:          TvarV[ncovv]=Tvar[k];
                   11399:          TvarVind[ncovv]=k;
                   11400:        }
1.227     brouard  11401:       }else{
1.240     brouard  11402:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11403:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11404:       } /*end k1*/
1.225     brouard  11405:     }else{
1.226     brouard  11406:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11407:       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  11408:     }
1.342   ! brouard  11409:     /* 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]); */
        !          11410:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  11411:     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]);
                   11412:   }
                   11413:   /* Searching for doublons in the model */
                   11414:   for(k1=1; k1<= cptcovt;k1++){
                   11415:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11416:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11417:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11418:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11419:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11420:            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]);
                   11421:            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  11422:            return(1);
                   11423:          }
                   11424:        }else if (Typevar[k1] ==2){
                   11425:          k3=Tposprod[k1];
                   11426:          k4=Tposprod[k2];
                   11427:          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  11428:            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]]);
                   11429:            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  11430:            return(1);
                   11431:          }
                   11432:        }
1.227     brouard  11433:       }
                   11434:     }
1.225     brouard  11435:   }
                   11436:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11437:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11438:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11439:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11440:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11441:   /*endread:*/
1.225     brouard  11442:   printf("Exiting decodemodel: ");
                   11443:   return (1);
1.136     brouard  11444: }
                   11445: 
1.169     brouard  11446: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11447: {/* Check ages at death */
1.136     brouard  11448:   int i, m;
1.218     brouard  11449:   int firstone=0;
                   11450:   
1.136     brouard  11451:   for (i=1; i<=imx; i++) {
                   11452:     for(m=2; (m<= maxwav); m++) {
                   11453:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11454:        anint[m][i]=9999;
1.216     brouard  11455:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11456:          s[m][i]=-1;
1.136     brouard  11457:       }
                   11458:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11459:        *nberr = *nberr + 1;
1.218     brouard  11460:        if(firstone == 0){
                   11461:          firstone=1;
1.260     brouard  11462:        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  11463:        }
1.262     brouard  11464:        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  11465:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11466:       }
                   11467:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11468:        (*nberr)++;
1.259     brouard  11469:        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  11470:        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  11471:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11472:       }
                   11473:     }
                   11474:   }
                   11475: 
                   11476:   for (i=1; i<=imx; i++)  {
                   11477:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11478:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11479:       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  11480:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11481:          if(agedc[i]>0){
                   11482:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11483:              agev[m][i]=agedc[i];
1.214     brouard  11484:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11485:            }else {
1.136     brouard  11486:              if ((int)andc[i]!=9999){
                   11487:                nbwarn++;
                   11488:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11489:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11490:                agev[m][i]=-1;
                   11491:              }
                   11492:            }
1.169     brouard  11493:          } /* agedc > 0 */
1.214     brouard  11494:        } /* end if */
1.136     brouard  11495:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11496:                                 years but with the precision of a month */
                   11497:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11498:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11499:            agev[m][i]=1;
                   11500:          else if(agev[m][i] < *agemin){ 
                   11501:            *agemin=agev[m][i];
                   11502:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11503:          }
                   11504:          else if(agev[m][i] >*agemax){
                   11505:            *agemax=agev[m][i];
1.156     brouard  11506:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11507:          }
                   11508:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11509:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11510:        } /* en if 9*/
1.136     brouard  11511:        else { /* =9 */
1.214     brouard  11512:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11513:          agev[m][i]=1;
                   11514:          s[m][i]=-1;
                   11515:        }
                   11516:       }
1.214     brouard  11517:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11518:        agev[m][i]=1;
1.214     brouard  11519:       else{
                   11520:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11521:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11522:        agev[m][i]=0;
                   11523:       }
                   11524:     } /* End for lastpass */
                   11525:   }
1.136     brouard  11526:     
                   11527:   for (i=1; i<=imx; i++)  {
                   11528:     for(m=firstpass; (m<=lastpass); m++){
                   11529:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11530:        (*nberr)++;
1.136     brouard  11531:        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);     
                   11532:        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);     
                   11533:        return 1;
                   11534:       }
                   11535:     }
                   11536:   }
                   11537: 
                   11538:   /*for (i=1; i<=imx; i++){
                   11539:   for (m=firstpass; (m<lastpass); m++){
                   11540:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11541: }
                   11542: 
                   11543: }*/
                   11544: 
                   11545: 
1.139     brouard  11546:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11547:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11548: 
                   11549:   return (0);
1.164     brouard  11550:  /* endread:*/
1.136     brouard  11551:     printf("Exiting calandcheckages: ");
                   11552:     return (1);
                   11553: }
                   11554: 
1.172     brouard  11555: #if defined(_MSC_VER)
                   11556: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11557: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11558: //#include "stdafx.h"
                   11559: //#include <stdio.h>
                   11560: //#include <tchar.h>
                   11561: //#include <windows.h>
                   11562: //#include <iostream>
                   11563: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11564: 
                   11565: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11566: 
                   11567: BOOL IsWow64()
                   11568: {
                   11569:        BOOL bIsWow64 = FALSE;
                   11570: 
                   11571:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11572:        //  (HANDLE, PBOOL);
                   11573: 
                   11574:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11575: 
                   11576:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11577:        const char funcName[] = "IsWow64Process";
                   11578:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11579:                GetProcAddress(module, funcName);
                   11580: 
                   11581:        if (NULL != fnIsWow64Process)
                   11582:        {
                   11583:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11584:                        &bIsWow64))
                   11585:                        //throw std::exception("Unknown error");
                   11586:                        printf("Unknown error\n");
                   11587:        }
                   11588:        return bIsWow64 != FALSE;
                   11589: }
                   11590: #endif
1.177     brouard  11591: 
1.191     brouard  11592: void syscompilerinfo(int logged)
1.292     brouard  11593: {
                   11594: #include <stdint.h>
                   11595: 
                   11596:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11597:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11598:    /* /GS /W3 /Gy
                   11599:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11600:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11601:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11602:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11603:    */ 
                   11604:    /* 64 bits */
1.185     brouard  11605:    /*
                   11606:      /GS /W3 /Gy
                   11607:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11608:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11609:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11610:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11611:    /* Optimization are useless and O3 is slower than O2 */
                   11612:    /*
                   11613:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11614:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11615:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11616:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11617:    */
1.186     brouard  11618:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11619:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11620:       /PDB:"visual studio
                   11621:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11622:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11623:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11624:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11625:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11626:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11627:       uiAccess='false'"
                   11628:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11629:       /NOLOGO /TLBID:1
                   11630:    */
1.292     brouard  11631: 
                   11632: 
1.177     brouard  11633: #if defined __INTEL_COMPILER
1.178     brouard  11634: #if defined(__GNUC__)
                   11635:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11636: #endif
1.177     brouard  11637: #elif defined(__GNUC__) 
1.179     brouard  11638: #ifndef  __APPLE__
1.174     brouard  11639: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11640: #endif
1.177     brouard  11641:    struct utsname sysInfo;
1.178     brouard  11642:    int cross = CROSS;
                   11643:    if (cross){
                   11644:           printf("Cross-");
1.191     brouard  11645:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11646:    }
1.174     brouard  11647: #endif
                   11648: 
1.191     brouard  11649:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11650: #if defined(__clang__)
1.191     brouard  11651:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11652: #endif
                   11653: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11654:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11655: #endif
                   11656: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11657:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11658: #endif
                   11659: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11660:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11661: #endif
                   11662: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11663:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11664: #endif
                   11665: #if defined(_MSC_VER)
1.191     brouard  11666:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11667: #endif
                   11668: #if defined(__PGI)
1.191     brouard  11669:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11670: #endif
                   11671: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11672:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11673: #endif
1.191     brouard  11674:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11675:    
1.167     brouard  11676: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11677: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11678:     // Windows (x64 and x86)
1.191     brouard  11679:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11680: #elif __unix__ // all unices, not all compilers
                   11681:     // Unix
1.191     brouard  11682:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11683: #elif __linux__
                   11684:     // linux
1.191     brouard  11685:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11686: #elif __APPLE__
1.174     brouard  11687:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11688:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11689: #endif
                   11690: 
                   11691: /*  __MINGW32__          */
                   11692: /*  __CYGWIN__  */
                   11693: /* __MINGW64__  */
                   11694: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11695: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11696: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11697: /* _WIN64  // Defined for applications for Win64. */
                   11698: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11699: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11700: 
1.167     brouard  11701: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11702:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11703: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11704:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11705: #else
1.191     brouard  11706:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11707: #endif
                   11708: 
1.169     brouard  11709: #if defined(__GNUC__)
                   11710: # if defined(__GNUC_PATCHLEVEL__)
                   11711: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11712:                             + __GNUC_MINOR__ * 100 \
                   11713:                             + __GNUC_PATCHLEVEL__)
                   11714: # else
                   11715: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11716:                             + __GNUC_MINOR__ * 100)
                   11717: # endif
1.174     brouard  11718:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11719:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11720: 
                   11721:    if (uname(&sysInfo) != -1) {
                   11722:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11723:         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  11724:    }
                   11725:    else
                   11726:       perror("uname() error");
1.179     brouard  11727:    //#ifndef __INTEL_COMPILER 
                   11728: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11729:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11730:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11731: #endif
1.169     brouard  11732: #endif
1.172     brouard  11733: 
1.286     brouard  11734:    //   void main ()
1.172     brouard  11735:    //   {
1.169     brouard  11736: #if defined(_MSC_VER)
1.174     brouard  11737:    if (IsWow64()){
1.191     brouard  11738:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11739:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11740:    }
                   11741:    else{
1.191     brouard  11742:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11743:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11744:    }
1.172     brouard  11745:    //     printf("\nPress Enter to continue...");
                   11746:    //     getchar();
                   11747:    //   }
                   11748: 
1.169     brouard  11749: #endif
                   11750:    
1.167     brouard  11751: 
1.219     brouard  11752: }
1.136     brouard  11753: 
1.219     brouard  11754: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11755:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11756:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11757:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11758:   /* double ftolpl = 1.e-10; */
1.180     brouard  11759:   double age, agebase, agelim;
1.203     brouard  11760:   double tot;
1.180     brouard  11761: 
1.202     brouard  11762:   strcpy(filerespl,"PL_");
                   11763:   strcat(filerespl,fileresu);
                   11764:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11765:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11766:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11767:   }
1.288     brouard  11768:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11769:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11770:   pstamp(ficrespl);
1.288     brouard  11771:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11772:   fprintf(ficrespl,"#Age ");
                   11773:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11774:   fprintf(ficrespl,"\n");
1.180     brouard  11775:   
1.219     brouard  11776:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11777: 
1.219     brouard  11778:   agebase=ageminpar;
                   11779:   agelim=agemaxpar;
1.180     brouard  11780: 
1.227     brouard  11781:   /* i1=pow(2,ncoveff); */
1.234     brouard  11782:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11783:   if (cptcovn < 1){i1=1;}
1.180     brouard  11784: 
1.337     brouard  11785:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11786:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11787:       k=TKresult[nres];
1.338     brouard  11788:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11789:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11790:       /*       continue; */
1.235     brouard  11791: 
1.238     brouard  11792:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11793:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11794:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11795:       /* k=k+1; */
                   11796:       /* to clean */
1.332     brouard  11797:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11798:       fprintf(ficrespl,"#******");
                   11799:       printf("#******");
                   11800:       fprintf(ficlog,"#******");
1.337     brouard  11801:       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  11802:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11803:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11804:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11805:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11806:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11807:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11808:       }
                   11809:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11810:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11811:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11812:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11813:       /* } */
1.238     brouard  11814:       fprintf(ficrespl,"******\n");
                   11815:       printf("******\n");
                   11816:       fprintf(ficlog,"******\n");
                   11817:       if(invalidvarcomb[k]){
                   11818:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11819:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11820:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11821:        continue;
                   11822:       }
1.219     brouard  11823: 
1.238     brouard  11824:       fprintf(ficrespl,"#Age ");
1.337     brouard  11825:       /* for(j=1;j<=cptcoveff;j++) { */
                   11826:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11827:       /* } */
                   11828:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   11829:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11830:       }
                   11831:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11832:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11833:     
1.238     brouard  11834:       for (age=agebase; age<=agelim; age++){
                   11835:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  11836:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   11837:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  11838:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  11839:        /* for(j=1;j<=cptcoveff;j++) */
                   11840:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11841:        for(j=1;j<=cptcovs;j++)
                   11842:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11843:        tot=0.;
                   11844:        for(i=1; i<=nlstate;i++){
                   11845:          tot +=  prlim[i][i];
                   11846:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11847:        }
                   11848:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11849:       } /* Age */
                   11850:       /* was end of cptcod */
1.337     brouard  11851:     } /* nres */
                   11852:   /* } /\* for each combination *\/ */
1.219     brouard  11853:   return 0;
1.180     brouard  11854: }
                   11855: 
1.218     brouard  11856: 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  11857:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11858:        
                   11859:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11860:    * at any age between ageminpar and agemaxpar
                   11861:         */
1.235     brouard  11862:   int i, j, k, i1, nres=0 ;
1.217     brouard  11863:   /* double ftolpl = 1.e-10; */
                   11864:   double age, agebase, agelim;
                   11865:   double tot;
1.218     brouard  11866:   /* double ***mobaverage; */
                   11867:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11868: 
                   11869:   strcpy(fileresplb,"PLB_");
                   11870:   strcat(fileresplb,fileresu);
                   11871:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11872:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11873:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11874:   }
1.288     brouard  11875:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11876:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11877:   pstamp(ficresplb);
1.288     brouard  11878:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11879:   fprintf(ficresplb,"#Age ");
                   11880:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11881:   fprintf(ficresplb,"\n");
                   11882:   
1.218     brouard  11883:   
                   11884:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11885:   
                   11886:   agebase=ageminpar;
                   11887:   agelim=agemaxpar;
                   11888:   
                   11889:   
1.227     brouard  11890:   i1=pow(2,cptcoveff);
1.218     brouard  11891:   if (cptcovn < 1){i1=1;}
1.227     brouard  11892:   
1.238     brouard  11893:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  11894:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   11895:       k=TKresult[nres];
                   11896:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11897:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   11898:      /*        continue; */
                   11899:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  11900:       fprintf(ficresplb,"#******");
                   11901:       printf("#******");
                   11902:       fprintf(ficlog,"#******");
1.338     brouard  11903:       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) */
                   11904:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11905:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11906:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11907:       }
1.338     brouard  11908:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   11909:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11910:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11911:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11912:       /* } */
                   11913:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11914:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11915:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11916:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11917:       /* } */
1.238     brouard  11918:       fprintf(ficresplb,"******\n");
                   11919:       printf("******\n");
                   11920:       fprintf(ficlog,"******\n");
                   11921:       if(invalidvarcomb[k]){
                   11922:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11923:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11924:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11925:        continue;
                   11926:       }
1.218     brouard  11927:     
1.238     brouard  11928:       fprintf(ficresplb,"#Age ");
1.338     brouard  11929:       for(j=1;j<=cptcovs;j++) {
                   11930:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11931:       }
                   11932:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11933:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11934:     
                   11935:     
1.238     brouard  11936:       for (age=agebase; age<=agelim; age++){
                   11937:        /* for (age=agebase; age<=agebase; age++){ */
                   11938:        if(mobilavproj > 0){
                   11939:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11940:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11941:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11942:        }else if (mobilavproj == 0){
                   11943:          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);
                   11944:          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);
                   11945:          exit(1);
                   11946:        }else{
                   11947:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11948:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11949:          /* printf("TOTOT\n"); */
                   11950:           /* exit(1); */
1.238     brouard  11951:        }
                   11952:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  11953:        for(j=1;j<=cptcovs;j++)
                   11954:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11955:        tot=0.;
                   11956:        for(i=1; i<=nlstate;i++){
                   11957:          tot +=  bprlim[i][i];
                   11958:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11959:        }
                   11960:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11961:       } /* Age */
                   11962:       /* was end of cptcod */
1.255     brouard  11963:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  11964:     /* } /\* end of any combination *\/ */
1.238     brouard  11965:   } /* end of nres */  
1.218     brouard  11966:   /* hBijx(p, bage, fage); */
                   11967:   /* fclose(ficrespijb); */
                   11968:   
                   11969:   return 0;
1.217     brouard  11970: }
1.218     brouard  11971:  
1.180     brouard  11972: int hPijx(double *p, int bage, int fage){
                   11973:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  11974:   /* to be optimized with precov */
1.180     brouard  11975:   int stepsize;
                   11976:   int agelim;
                   11977:   int hstepm;
                   11978:   int nhstepm;
1.235     brouard  11979:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11980: 
                   11981:   double agedeb;
                   11982:   double ***p3mat;
                   11983: 
1.337     brouard  11984:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   11985:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11986:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11987:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11988:   }
                   11989:   printf("Computing pij: result on file '%s' \n", filerespij);
                   11990:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11991:   
                   11992:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11993:   /*if (stepm<=24) stepsize=2;*/
                   11994:   
                   11995:   agelim=AGESUP;
                   11996:   hstepm=stepsize*YEARM; /* Every year of age */
                   11997:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   11998:   
                   11999:   /* hstepm=1;   aff par mois*/
                   12000:   pstamp(ficrespij);
                   12001:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12002:   i1= pow(2,cptcoveff);
                   12003:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12004:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12005:   /*   k=k+1;  */
                   12006:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12007:     k=TKresult[nres];
1.338     brouard  12008:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12009:     /* for(k=1; k<=i1;k++){ */
                   12010:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12011:     /*         continue; */
                   12012:     fprintf(ficrespij,"\n#****** ");
                   12013:     for(j=1;j<=cptcovs;j++){
                   12014:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12015:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12016:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12017:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12018:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12019:     }
                   12020:     fprintf(ficrespij,"******\n");
                   12021:     
                   12022:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12023:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12024:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12025:       
                   12026:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12027:       
                   12028:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12029:       oldm=oldms;savm=savms;
                   12030:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12031:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12032:       for(i=1; i<=nlstate;i++)
                   12033:        for(j=1; j<=nlstate+ndeath;j++)
                   12034:          fprintf(ficrespij," %1d-%1d",i,j);
                   12035:       fprintf(ficrespij,"\n");
                   12036:       for (h=0; h<=nhstepm; h++){
                   12037:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12038:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12039:        for(i=1; i<=nlstate;i++)
                   12040:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12041:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12042:        fprintf(ficrespij,"\n");
                   12043:       }
1.337     brouard  12044:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12045:       fprintf(ficrespij,"\n");
1.180     brouard  12046:     }
1.337     brouard  12047:   }
                   12048:   /*}*/
                   12049:   return 0;
1.180     brouard  12050: }
1.218     brouard  12051:  
                   12052:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12053:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12054:     /* To be optimized with precov */
1.217     brouard  12055:   int stepsize;
1.218     brouard  12056:   /* int agelim; */
                   12057:        int ageminl;
1.217     brouard  12058:   int hstepm;
                   12059:   int nhstepm;
1.238     brouard  12060:   int h, i, i1, j, k, nres;
1.218     brouard  12061:        
1.217     brouard  12062:   double agedeb;
                   12063:   double ***p3mat;
1.218     brouard  12064:        
                   12065:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12066:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12067:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12068:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12069:   }
                   12070:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12071:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12072:   
                   12073:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12074:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12075:   
1.218     brouard  12076:   /* agelim=AGESUP; */
1.289     brouard  12077:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12078:   hstepm=stepsize*YEARM; /* Every year of age */
                   12079:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12080:   
                   12081:   /* hstepm=1;   aff par mois*/
                   12082:   pstamp(ficrespijb);
1.255     brouard  12083:   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  12084:   i1= pow(2,cptcoveff);
1.218     brouard  12085:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12086:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12087:   /*   k=k+1;  */
1.238     brouard  12088:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12089:     k=TKresult[nres];
1.338     brouard  12090:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12091:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12092:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12093:     /*         continue; */
                   12094:     fprintf(ficrespijb,"\n#****** ");
                   12095:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12096:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12097:       /* for(j=1;j<=cptcoveff;j++) */
                   12098:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12099:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12100:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12101:     }
                   12102:     fprintf(ficrespijb,"******\n");
                   12103:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12104:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12105:       continue;
                   12106:     }
                   12107:     
                   12108:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12109:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12110:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12111:       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 */
                   12112:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12113:       
                   12114:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12115:       
                   12116:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12117:       /* and memory limitations if stepm is small */
                   12118:       
                   12119:       /* oldm=oldms;savm=savms; */
                   12120:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12121:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12122:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12123:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12124:       for(i=1; i<=nlstate;i++)
                   12125:        for(j=1; j<=nlstate+ndeath;j++)
                   12126:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12127:       fprintf(ficrespijb,"\n");
                   12128:       for (h=0; h<=nhstepm; h++){
                   12129:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12130:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12131:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12132:        for(i=1; i<=nlstate;i++)
                   12133:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12134:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12135:        fprintf(ficrespijb,"\n");
1.337     brouard  12136:       }
                   12137:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12138:       fprintf(ficrespijb,"\n");
                   12139:     } /* end age deb */
                   12140:     /* } /\* end combination *\/ */
1.238     brouard  12141:   } /* end nres */
1.218     brouard  12142:   return 0;
                   12143:  } /*  hBijx */
1.217     brouard  12144: 
1.180     brouard  12145: 
1.136     brouard  12146: /***********************************************/
                   12147: /**************** Main Program *****************/
                   12148: /***********************************************/
                   12149: 
                   12150: int main(int argc, char *argv[])
                   12151: {
                   12152: #ifdef GSL
                   12153:   const gsl_multimin_fminimizer_type *T;
                   12154:   size_t iteri = 0, it;
                   12155:   int rval = GSL_CONTINUE;
                   12156:   int status = GSL_SUCCESS;
                   12157:   double ssval;
                   12158: #endif
                   12159:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12160:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12161:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12162:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12163:   int jj, ll, li, lj, lk;
1.136     brouard  12164:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12165:   int num_filled;
1.136     brouard  12166:   int itimes;
                   12167:   int NDIM=2;
                   12168:   int vpopbased=0;
1.235     brouard  12169:   int nres=0;
1.258     brouard  12170:   int endishere=0;
1.277     brouard  12171:   int noffset=0;
1.274     brouard  12172:   int ncurrv=0; /* Temporary variable */
                   12173:   
1.164     brouard  12174:   char ca[32], cb[32];
1.136     brouard  12175:   /*  FILE *fichtm; *//* Html File */
                   12176:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12177:   struct stat info;
1.191     brouard  12178:   double agedeb=0.;
1.194     brouard  12179: 
                   12180:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12181:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12182: 
1.165     brouard  12183:   double fret;
1.191     brouard  12184:   double dum=0.; /* Dummy variable */
1.136     brouard  12185:   double ***p3mat;
1.218     brouard  12186:   /* double ***mobaverage; */
1.319     brouard  12187:   double wald;
1.164     brouard  12188: 
                   12189:   char line[MAXLINE];
1.197     brouard  12190:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12191: 
1.234     brouard  12192:   char  modeltemp[MAXLINE];
1.332     brouard  12193:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12194:   
1.136     brouard  12195:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12196:   char *tok, *val; /* pathtot */
1.334     brouard  12197:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12198:   int c,  h , cpt, c2;
1.191     brouard  12199:   int jl=0;
                   12200:   int i1, j1, jk, stepsize=0;
1.194     brouard  12201:   int count=0;
                   12202: 
1.164     brouard  12203:   int *tab; 
1.136     brouard  12204:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12205:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12206:   /* double anprojf, mprojf, jprojf; */
                   12207:   /* double jintmean,mintmean,aintmean;   */
                   12208:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12209:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12210:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12211:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12212:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12213:   int mobilav=0,popforecast=0;
1.191     brouard  12214:   int hstepm=0, nhstepm=0;
1.136     brouard  12215:   int agemortsup;
                   12216:   float  sumlpop=0.;
                   12217:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12218:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12219: 
1.191     brouard  12220:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12221:   double ftolpl=FTOL;
                   12222:   double **prlim;
1.217     brouard  12223:   double **bprlim;
1.317     brouard  12224:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12225:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12226:   double ***paramstart; /* Matrix of starting parameter values */
                   12227:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12228:   double **matcov; /* Matrix of covariance */
1.203     brouard  12229:   double **hess; /* Hessian matrix */
1.136     brouard  12230:   double ***delti3; /* Scale */
                   12231:   double *delti; /* Scale */
                   12232:   double ***eij, ***vareij;
                   12233:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12234: 
1.136     brouard  12235:   double *epj, vepp;
1.164     brouard  12236: 
1.273     brouard  12237:   double dateprev1, dateprev2;
1.296     brouard  12238:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12239:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12240: 
1.217     brouard  12241: 
1.136     brouard  12242:   double **ximort;
1.145     brouard  12243:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12244:   int *dcwave;
                   12245: 
1.164     brouard  12246:   char z[1]="c";
1.136     brouard  12247: 
                   12248:   /*char  *strt;*/
                   12249:   char strtend[80];
1.126     brouard  12250: 
1.164     brouard  12251: 
1.126     brouard  12252: /*   setlocale (LC_ALL, ""); */
                   12253: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12254: /*   textdomain (PACKAGE); */
                   12255: /*   setlocale (LC_CTYPE, ""); */
                   12256: /*   setlocale (LC_MESSAGES, ""); */
                   12257: 
                   12258:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12259:   rstart_time = time(NULL);  
                   12260:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12261:   start_time = *localtime(&rstart_time);
1.126     brouard  12262:   curr_time=start_time;
1.157     brouard  12263:   /*tml = *localtime(&start_time.tm_sec);*/
                   12264:   /* strcpy(strstart,asctime(&tml)); */
                   12265:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12266: 
                   12267: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12268: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12269: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12270: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12271: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12272: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12273: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12274: /*   strt=asctime(&tmg); */
                   12275: /*   printf("Time(after) =%s",strstart);  */
                   12276: /*  (void) time (&time_value);
                   12277: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12278: *  tm = *localtime(&time_value);
                   12279: *  strstart=asctime(&tm);
                   12280: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12281: */
                   12282: 
                   12283:   nberr=0; /* Number of errors and warnings */
                   12284:   nbwarn=0;
1.184     brouard  12285: #ifdef WIN32
                   12286:   _getcwd(pathcd, size);
                   12287: #else
1.126     brouard  12288:   getcwd(pathcd, size);
1.184     brouard  12289: #endif
1.191     brouard  12290:   syscompilerinfo(0);
1.196     brouard  12291:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12292:   if(argc <=1){
                   12293:     printf("\nEnter the parameter file name: ");
1.205     brouard  12294:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12295:       printf("ERROR Empty parameter file name\n");
                   12296:       goto end;
                   12297:     }
1.126     brouard  12298:     i=strlen(pathr);
                   12299:     if(pathr[i-1]=='\n')
                   12300:       pathr[i-1]='\0';
1.156     brouard  12301:     i=strlen(pathr);
1.205     brouard  12302:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12303:       pathr[i-1]='\0';
1.205     brouard  12304:     }
                   12305:     i=strlen(pathr);
                   12306:     if( i==0 ){
                   12307:       printf("ERROR Empty parameter file name\n");
                   12308:       goto end;
                   12309:     }
                   12310:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12311:       printf("Pathr |%s|\n",pathr);
                   12312:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12313:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12314:       strcpy (pathtot, val);
                   12315:       if(pathr[0] == '\0') break; /* Dirty */
                   12316:     }
                   12317:   }
1.281     brouard  12318:   else if (argc<=2){
                   12319:     strcpy(pathtot,argv[1]);
                   12320:   }
1.126     brouard  12321:   else{
                   12322:     strcpy(pathtot,argv[1]);
1.281     brouard  12323:     strcpy(z,argv[2]);
                   12324:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12325:   }
                   12326:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12327:   /*cygwin_split_path(pathtot,path,optionfile);
                   12328:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12329:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12330: 
                   12331:   /* Split argv[0], imach program to get pathimach */
                   12332:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12333:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12334:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12335:  /*   strcpy(pathimach,argv[0]); */
                   12336:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12337:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12338:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12339: #ifdef WIN32
                   12340:   _chdir(path); /* Can be a relative path */
                   12341:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12342: #else
1.126     brouard  12343:   chdir(path); /* Can be a relative path */
1.184     brouard  12344:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12345: #endif
                   12346:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12347:   strcpy(command,"mkdir ");
                   12348:   strcat(command,optionfilefiname);
                   12349:   if((outcmd=system(command)) != 0){
1.169     brouard  12350:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12351:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12352:     /* fclose(ficlog); */
                   12353: /*     exit(1); */
                   12354:   }
                   12355: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12356: /*     perror("mkdir"); */
                   12357: /*   } */
                   12358: 
                   12359:   /*-------- arguments in the command line --------*/
                   12360: 
1.186     brouard  12361:   /* Main Log file */
1.126     brouard  12362:   strcat(filelog, optionfilefiname);
                   12363:   strcat(filelog,".log");    /* */
                   12364:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12365:     printf("Problem with logfile %s\n",filelog);
                   12366:     goto end;
                   12367:   }
                   12368:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12369:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12370:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12371:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12372:  path=%s \n\
                   12373:  optionfile=%s\n\
                   12374:  optionfilext=%s\n\
1.156     brouard  12375:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12376: 
1.197     brouard  12377:   syscompilerinfo(1);
1.167     brouard  12378: 
1.126     brouard  12379:   printf("Local time (at start):%s",strstart);
                   12380:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12381:   fflush(ficlog);
                   12382: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12383: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12384: 
                   12385:   /* */
                   12386:   strcpy(fileres,"r");
                   12387:   strcat(fileres, optionfilefiname);
1.201     brouard  12388:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12389:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12390:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12391: 
1.186     brouard  12392:   /* Main ---------arguments file --------*/
1.126     brouard  12393: 
                   12394:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12395:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12396:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12397:     fflush(ficlog);
1.149     brouard  12398:     /* goto end; */
                   12399:     exit(70); 
1.126     brouard  12400:   }
                   12401: 
                   12402:   strcpy(filereso,"o");
1.201     brouard  12403:   strcat(filereso,fileresu);
1.126     brouard  12404:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12405:     printf("Problem with Output resultfile: %s\n", filereso);
                   12406:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12407:     fflush(ficlog);
                   12408:     goto end;
                   12409:   }
1.278     brouard  12410:       /*-------- Rewriting parameter file ----------*/
                   12411:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12412:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12413:   strcat(rfileres,".");    /* */
                   12414:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12415:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12416:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12417:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12418:     fflush(ficlog);
                   12419:     goto end;
                   12420:   }
                   12421:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12422: 
1.278     brouard  12423:                                      
1.126     brouard  12424:   /* Reads comments: lines beginning with '#' */
                   12425:   numlinepar=0;
1.277     brouard  12426:   /* Is it a BOM UTF-8 Windows file? */
                   12427:   /* First parameter line */
1.197     brouard  12428:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12429:     noffset=0;
                   12430:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12431:     {
                   12432:       noffset=noffset+3;
                   12433:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12434:     }
1.302     brouard  12435: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12436:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12437:     {
                   12438:       noffset=noffset+2;
                   12439:       printf("# File is an UTF16BE BOM file\n");
                   12440:     }
                   12441:     else if( line[0] == 0 && line[1] == 0)
                   12442:     {
                   12443:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12444:        noffset=noffset+4;
                   12445:        printf("# File is an UTF16BE BOM file\n");
                   12446:       }
                   12447:     } else{
                   12448:       ;/*printf(" Not a BOM file\n");*/
                   12449:     }
                   12450:   
1.197     brouard  12451:     /* If line starts with a # it is a comment */
1.277     brouard  12452:     if (line[noffset] == '#') {
1.197     brouard  12453:       numlinepar++;
                   12454:       fputs(line,stdout);
                   12455:       fputs(line,ficparo);
1.278     brouard  12456:       fputs(line,ficres);
1.197     brouard  12457:       fputs(line,ficlog);
                   12458:       continue;
                   12459:     }else
                   12460:       break;
                   12461:   }
                   12462:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12463:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12464:     if (num_filled != 5) {
                   12465:       printf("Should be 5 parameters\n");
1.283     brouard  12466:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12467:     }
1.126     brouard  12468:     numlinepar++;
1.197     brouard  12469:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12470:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12471:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12472:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12473:   }
                   12474:   /* Second parameter line */
                   12475:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12476:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12477:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12478:     if (line[0] == '#') {
                   12479:       numlinepar++;
1.283     brouard  12480:       printf("%s",line);
                   12481:       fprintf(ficres,"%s",line);
                   12482:       fprintf(ficparo,"%s",line);
                   12483:       fprintf(ficlog,"%s",line);
1.197     brouard  12484:       continue;
                   12485:     }else
                   12486:       break;
                   12487:   }
1.223     brouard  12488:   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", \
                   12489:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12490:     if (num_filled != 11) {
                   12491:       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  12492:       printf("but line=%s\n",line);
1.283     brouard  12493:       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");
                   12494:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12495:     }
1.286     brouard  12496:     if( lastpass > maxwav){
                   12497:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12498:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12499:       fflush(ficlog);
                   12500:       goto end;
                   12501:     }
                   12502:       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  12503:     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  12504:     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  12505:     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  12506:   }
1.203     brouard  12507:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12508:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12509:   /* Third parameter line */
                   12510:   while(fgets(line, MAXLINE, ficpar)) {
                   12511:     /* If line starts with a # it is a comment */
                   12512:     if (line[0] == '#') {
                   12513:       numlinepar++;
1.283     brouard  12514:       printf("%s",line);
                   12515:       fprintf(ficres,"%s",line);
                   12516:       fprintf(ficparo,"%s",line);
                   12517:       fprintf(ficlog,"%s",line);
1.197     brouard  12518:       continue;
                   12519:     }else
                   12520:       break;
                   12521:   }
1.201     brouard  12522:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12523:     if (num_filled != 1){
1.302     brouard  12524:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12525:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12526:       model[0]='\0';
                   12527:       goto end;
                   12528:     }
                   12529:     else{
                   12530:       if (model[0]=='+'){
                   12531:        for(i=1; i<=strlen(model);i++)
                   12532:          modeltemp[i-1]=model[i];
1.201     brouard  12533:        strcpy(model,modeltemp); 
1.197     brouard  12534:       }
                   12535:     }
1.338     brouard  12536:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12537:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12538:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12539:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12540:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12541:   }
                   12542:   /* 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); */
                   12543:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12544:   /* 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  12545:   /* 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); */
                   12546:   /* 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  12547:   fflush(ficlog);
1.190     brouard  12548:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12549:   if(model[0]=='#'){
1.279     brouard  12550:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12551:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12552:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12553:     if(mle != -1){
1.279     brouard  12554:       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  12555:       exit(1);
                   12556:     }
                   12557:   }
1.126     brouard  12558:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12559:     ungetc(c,ficpar);
                   12560:     fgets(line, MAXLINE, ficpar);
                   12561:     numlinepar++;
1.195     brouard  12562:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12563:       z[0]=line[1];
1.342   ! brouard  12564:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
        !          12565:       debugILK=1;
1.195     brouard  12566:     }
                   12567:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12568:     fputs(line, stdout);
                   12569:     //puts(line);
1.126     brouard  12570:     fputs(line,ficparo);
                   12571:     fputs(line,ficlog);
                   12572:   }
                   12573:   ungetc(c,ficpar);
                   12574: 
                   12575:    
1.290     brouard  12576:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12577:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12578:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  12579:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   12580:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12581:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12582:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12583:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12584:   */
                   12585:   if (strlen(model)>1) 
1.187     brouard  12586:     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  12587:   else
1.187     brouard  12588:     ncovmodel=2; /* Constant and age */
1.133     brouard  12589:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12590:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12591:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12592:     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);
                   12593:     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);
                   12594:     fflush(stdout);
                   12595:     fclose (ficlog);
                   12596:     goto end;
                   12597:   }
1.126     brouard  12598:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12599:   delti=delti3[1][1];
                   12600:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12601:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12602: /* We could also provide initial parameters values giving by simple logistic regression 
                   12603:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12604:       /* for(i=1;i<nlstate;i++){ */
                   12605:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12606:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12607:       /* } */
1.126     brouard  12608:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12609:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12610:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12611:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12612:     fclose (ficparo);
                   12613:     fclose (ficlog);
                   12614:     goto end;
                   12615:     exit(0);
1.220     brouard  12616:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12617:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12618:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12619:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12620:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12621:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12622:     hess=matrix(1,npar,1,npar);
1.220     brouard  12623:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12624:     /* Read guessed parameters */
1.126     brouard  12625:     /* Reads comments: lines beginning with '#' */
                   12626:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12627:       ungetc(c,ficpar);
                   12628:       fgets(line, MAXLINE, ficpar);
                   12629:       numlinepar++;
1.141     brouard  12630:       fputs(line,stdout);
1.126     brouard  12631:       fputs(line,ficparo);
                   12632:       fputs(line,ficlog);
                   12633:     }
                   12634:     ungetc(c,ficpar);
                   12635:     
                   12636:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12637:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12638:     for(i=1; i <=nlstate; i++){
1.234     brouard  12639:       j=0;
1.126     brouard  12640:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12641:        if(jj==i) continue;
                   12642:        j++;
1.292     brouard  12643:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12644:          ungetc(c,ficpar);
                   12645:          fgets(line, MAXLINE, ficpar);
                   12646:          numlinepar++;
                   12647:          fputs(line,stdout);
                   12648:          fputs(line,ficparo);
                   12649:          fputs(line,ficlog);
                   12650:        }
                   12651:        ungetc(c,ficpar);
1.234     brouard  12652:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12653:        if ((i1 != i) || (j1 != jj)){
                   12654:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12655: It might be a problem of design; if ncovcol and the model are correct\n \
                   12656: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12657:          exit(1);
                   12658:        }
                   12659:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12660:        if(mle==1)
                   12661:          printf("%1d%1d",i,jj);
                   12662:        fprintf(ficlog,"%1d%1d",i,jj);
                   12663:        for(k=1; k<=ncovmodel;k++){
                   12664:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12665:          if(mle==1){
                   12666:            printf(" %lf",param[i][j][k]);
                   12667:            fprintf(ficlog," %lf",param[i][j][k]);
                   12668:          }
                   12669:          else
                   12670:            fprintf(ficlog," %lf",param[i][j][k]);
                   12671:          fprintf(ficparo," %lf",param[i][j][k]);
                   12672:        }
                   12673:        fscanf(ficpar,"\n");
                   12674:        numlinepar++;
                   12675:        if(mle==1)
                   12676:          printf("\n");
                   12677:        fprintf(ficlog,"\n");
                   12678:        fprintf(ficparo,"\n");
1.126     brouard  12679:       }
                   12680:     }  
                   12681:     fflush(ficlog);
1.234     brouard  12682:     
1.251     brouard  12683:     /* Reads parameters values */
1.126     brouard  12684:     p=param[1][1];
1.251     brouard  12685:     pstart=paramstart[1][1];
1.126     brouard  12686:     
                   12687:     /* Reads comments: lines beginning with '#' */
                   12688:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12689:       ungetc(c,ficpar);
                   12690:       fgets(line, MAXLINE, ficpar);
                   12691:       numlinepar++;
1.141     brouard  12692:       fputs(line,stdout);
1.126     brouard  12693:       fputs(line,ficparo);
                   12694:       fputs(line,ficlog);
                   12695:     }
                   12696:     ungetc(c,ficpar);
                   12697: 
                   12698:     for(i=1; i <=nlstate; i++){
                   12699:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12700:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12701:        if ( (i1-i) * (j1-j) != 0){
                   12702:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12703:          exit(1);
                   12704:        }
                   12705:        printf("%1d%1d",i,j);
                   12706:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12707:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12708:        for(k=1; k<=ncovmodel;k++){
                   12709:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12710:          printf(" %le",delti3[i][j][k]);
                   12711:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12712:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12713:        }
                   12714:        fscanf(ficpar,"\n");
                   12715:        numlinepar++;
                   12716:        printf("\n");
                   12717:        fprintf(ficparo,"\n");
                   12718:        fprintf(ficlog,"\n");
1.126     brouard  12719:       }
                   12720:     }
                   12721:     fflush(ficlog);
1.234     brouard  12722:     
1.145     brouard  12723:     /* Reads covariance matrix */
1.126     brouard  12724:     delti=delti3[1][1];
1.220     brouard  12725:                
                   12726:                
1.126     brouard  12727:     /* 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  12728:                
1.126     brouard  12729:     /* Reads comments: lines beginning with '#' */
                   12730:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12731:       ungetc(c,ficpar);
                   12732:       fgets(line, MAXLINE, ficpar);
                   12733:       numlinepar++;
1.141     brouard  12734:       fputs(line,stdout);
1.126     brouard  12735:       fputs(line,ficparo);
                   12736:       fputs(line,ficlog);
                   12737:     }
                   12738:     ungetc(c,ficpar);
1.220     brouard  12739:                
1.126     brouard  12740:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12741:     hess=matrix(1,npar,1,npar);
1.131     brouard  12742:     for(i=1; i <=npar; i++)
                   12743:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12744:                
1.194     brouard  12745:     /* Scans npar lines */
1.126     brouard  12746:     for(i=1; i <=npar; i++){
1.226     brouard  12747:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12748:       if(count != 3){
1.226     brouard  12749:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12750: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12751: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12752:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12753: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12754: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12755:        exit(1);
1.220     brouard  12756:       }else{
1.226     brouard  12757:        if(mle==1)
                   12758:          printf("%1d%1d%d",i1,j1,jk);
                   12759:       }
                   12760:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12761:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12762:       for(j=1; j <=i; j++){
1.226     brouard  12763:        fscanf(ficpar," %le",&matcov[i][j]);
                   12764:        if(mle==1){
                   12765:          printf(" %.5le",matcov[i][j]);
                   12766:        }
                   12767:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12768:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12769:       }
                   12770:       fscanf(ficpar,"\n");
                   12771:       numlinepar++;
                   12772:       if(mle==1)
1.220     brouard  12773:                                printf("\n");
1.126     brouard  12774:       fprintf(ficlog,"\n");
                   12775:       fprintf(ficparo,"\n");
                   12776:     }
1.194     brouard  12777:     /* End of read covariance matrix npar lines */
1.126     brouard  12778:     for(i=1; i <=npar; i++)
                   12779:       for(j=i+1;j<=npar;j++)
1.226     brouard  12780:        matcov[i][j]=matcov[j][i];
1.126     brouard  12781:     
                   12782:     if(mle==1)
                   12783:       printf("\n");
                   12784:     fprintf(ficlog,"\n");
                   12785:     
                   12786:     fflush(ficlog);
                   12787:     
                   12788:   }    /* End of mle != -3 */
1.218     brouard  12789:   
1.186     brouard  12790:   /*  Main data
                   12791:    */
1.290     brouard  12792:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12793:   /* num=lvector(1,n); */
                   12794:   /* moisnais=vector(1,n); */
                   12795:   /* annais=vector(1,n); */
                   12796:   /* moisdc=vector(1,n); */
                   12797:   /* andc=vector(1,n); */
                   12798:   /* weight=vector(1,n); */
                   12799:   /* agedc=vector(1,n); */
                   12800:   /* cod=ivector(1,n); */
                   12801:   /* for(i=1;i<=n;i++){ */
                   12802:   num=lvector(firstobs,lastobs);
                   12803:   moisnais=vector(firstobs,lastobs);
                   12804:   annais=vector(firstobs,lastobs);
                   12805:   moisdc=vector(firstobs,lastobs);
                   12806:   andc=vector(firstobs,lastobs);
                   12807:   weight=vector(firstobs,lastobs);
                   12808:   agedc=vector(firstobs,lastobs);
                   12809:   cod=ivector(firstobs,lastobs);
                   12810:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12811:     num[i]=0;
                   12812:     moisnais[i]=0;
                   12813:     annais[i]=0;
                   12814:     moisdc[i]=0;
                   12815:     andc[i]=0;
                   12816:     agedc[i]=0;
                   12817:     cod[i]=0;
                   12818:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12819:   }
1.290     brouard  12820:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12821:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12822:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12823:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12824:   tab=ivector(1,NCOVMAX);
1.144     brouard  12825:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12826:   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  12827: 
1.136     brouard  12828:   /* Reads data from file datafile */
                   12829:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12830:     goto end;
                   12831: 
                   12832:   /* Calculation of the number of parameters from char model */
1.234     brouard  12833:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12834:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12835:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12836:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12837:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12838:   */
                   12839:   
                   12840:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12841:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12842:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12843:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12844:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12845:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12846:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12847:   TvarF=ivector(1,NCOVMAX); /*  */
                   12848:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12849:   TvarV=ivector(1,NCOVMAX); /*  */
                   12850:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12851:   TvarA=ivector(1,NCOVMAX); /*  */
                   12852:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12853:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12854:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12855:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12856:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12857:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12858:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12859:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12860:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  12861:   TvarVV=ivector(1,NCOVMAX); /*  */
                   12862:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12863: 
1.230     brouard  12864:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12865:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12866:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12867:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12868:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12869:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12870:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12871:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12872:   */
                   12873:   /* For model-covariate k tells which data-covariate to use but
                   12874:     because this model-covariate is a construction we invent a new column
                   12875:     ncovcol + k1
                   12876:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12877:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12878:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12879:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12880:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12881:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12882:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12883:   */
1.145     brouard  12884:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12885:   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  12886:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12887:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12888:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12889:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12890:                         4 covariates (3 plus signs)
                   12891:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12892:                           */  
                   12893:   for(i=1;i<NCOVMAX;i++)
                   12894:     Tage[i]=0;
1.230     brouard  12895:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12896:                                * individual dummy, fixed or varying:
                   12897:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12898:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12899:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12900:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12901:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12902:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12903:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12904:                                * individual quantitative, fixed or varying:
                   12905:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12906:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12907:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12908: /* Main decodemodel */
                   12909: 
1.187     brouard  12910: 
1.223     brouard  12911:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12912:     goto end;
                   12913: 
1.137     brouard  12914:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12915:     nbwarn++;
                   12916:     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); 
                   12917:     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); 
                   12918:   }
1.136     brouard  12919:     /*  if(mle==1){*/
1.137     brouard  12920:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12921:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12922:   }
                   12923: 
                   12924:     /*-calculation of age at interview from date of interview and age at death -*/
                   12925:   agev=matrix(1,maxwav,1,imx);
                   12926: 
                   12927:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12928:     goto end;
                   12929: 
1.126     brouard  12930: 
1.136     brouard  12931:   agegomp=(int)agemin;
1.290     brouard  12932:   free_vector(moisnais,firstobs,lastobs);
                   12933:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12934:   /* free_matrix(mint,1,maxwav,1,n);
                   12935:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12936:   /* free_vector(moisdc,1,n); */
                   12937:   /* free_vector(andc,1,n); */
1.145     brouard  12938:   /* */
                   12939:   
1.126     brouard  12940:   wav=ivector(1,imx);
1.214     brouard  12941:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12942:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12943:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12944:   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.*/
                   12945:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12946:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12947:    
                   12948:   /* Concatenates waves */
1.214     brouard  12949:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12950:      Death is a valid wave (if date is known).
                   12951:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12952:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12953:      and mw[mi+1][i]. dh depends on stepm.
                   12954:   */
                   12955: 
1.126     brouard  12956:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12957:   /* Concatenates waves */
1.145     brouard  12958:  
1.290     brouard  12959:   free_vector(moisdc,firstobs,lastobs);
                   12960:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12961: 
1.126     brouard  12962:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12963:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12964:   ncodemax[1]=1;
1.145     brouard  12965:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12966:   cptcoveff=0;
1.220     brouard  12967:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  12968:     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  12969:   }
                   12970:   
                   12971:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  12972:   invalidvarcomb=ivector(0, ncovcombmax); 
                   12973:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  12974:     invalidvarcomb[i]=0;
                   12975:   
1.211     brouard  12976:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12977:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12978:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12979:   
1.200     brouard  12980:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12981:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12982:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12983:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12984:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12985:    * (currently 0 or 1) in the data.
                   12986:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12987:    * corresponding modality (h,j).
                   12988:    */
                   12989: 
1.145     brouard  12990:   h=0;
                   12991:   /*if (cptcovn > 0) */
1.126     brouard  12992:   m=pow(2,cptcoveff);
                   12993:  
1.144     brouard  12994:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12995:           * For k=4 covariates, h goes from 1 to m=2**k
                   12996:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12997:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12998:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12999:           *______________________________   *______________________
                   13000:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13001:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13002:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13003:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13004:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13005:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13006:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13007:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13008:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13009:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13010:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13011:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13012:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13013:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13014:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13015:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13016:           */                                     
1.212     brouard  13017:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13018:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13019:      * and the value of each covariate?
                   13020:      * V1=1, V2=1, V3=2, V4=1 ?
                   13021:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13022:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13023:      * In order to get the real value in the data, we use nbcode
                   13024:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13025:      * We are keeping this crazy system in order to be able (in the future?) 
                   13026:      * to have more than 2 values (0 or 1) for a covariate.
                   13027:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13028:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13029:      *              bbbbbbbb
                   13030:      *              76543210     
                   13031:      *   h-1        00000101 (6-1=5)
1.219     brouard  13032:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13033:      *           &
                   13034:      *     1        00000001 (1)
1.219     brouard  13035:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13036:      *          +1= 00000001 =1 
1.211     brouard  13037:      *
                   13038:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13039:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13040:      *    >>k'            11
                   13041:      *          &   00000001
                   13042:      *            = 00000001
                   13043:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13044:      * Reverse h=6 and m=16?
                   13045:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13046:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13047:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13048:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13049:      * V3=decodtabm(14,3,2**4)=2
                   13050:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13051:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13052:      *          &1 000000001
                   13053:      *           = 000000001
                   13054:      *         +1= 000000010 =2
                   13055:      *                  2211
                   13056:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13057:      *                  V3=2
1.220     brouard  13058:                 * codtabm and decodtabm are identical
1.211     brouard  13059:      */
                   13060: 
1.145     brouard  13061: 
                   13062:  free_ivector(Ndum,-1,NCOVMAX);
                   13063: 
                   13064: 
1.126     brouard  13065:     
1.186     brouard  13066:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13067:   strcpy(optionfilegnuplot,optionfilefiname);
                   13068:   if(mle==-3)
1.201     brouard  13069:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13070:   strcat(optionfilegnuplot,".gp");
                   13071: 
                   13072:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13073:     printf("Problem with file %s",optionfilegnuplot);
                   13074:   }
                   13075:   else{
1.204     brouard  13076:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13077:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13078:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13079:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13080:   }
                   13081:   /*  fclose(ficgp);*/
1.186     brouard  13082: 
                   13083: 
                   13084:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13085: 
                   13086:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13087:   if(mle==-3)
1.201     brouard  13088:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13089:   strcat(optionfilehtm,".htm");
                   13090:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13091:     printf("Problem with %s \n",optionfilehtm);
                   13092:     exit(0);
1.126     brouard  13093:   }
                   13094: 
                   13095:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13096:   strcat(optionfilehtmcov,"-cov.htm");
                   13097:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13098:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13099:   }
                   13100:   else{
                   13101:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13102: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13103: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13104:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13105:   }
                   13106: 
1.335     brouard  13107:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13108: <title>IMaCh %s</title></head>\n\
                   13109:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13110: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13111: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13112: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13113: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13114:   
                   13115:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13116: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13117: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13118: 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  13119: \n\
                   13120: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13121:  <ul><li><h4>Parameter files</h4>\n\
                   13122:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13123:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13124:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13125:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13126:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13127:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13128:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13129:          fileres,fileres,\
                   13130:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13131:   fflush(fichtm);
                   13132: 
                   13133:   strcpy(pathr,path);
                   13134:   strcat(pathr,optionfilefiname);
1.184     brouard  13135: #ifdef WIN32
                   13136:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13137: #else
1.126     brouard  13138:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13139: #endif
                   13140:          
1.126     brouard  13141:   
1.220     brouard  13142:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13143:                 and for any valid combination of covariates
1.126     brouard  13144:      and prints on file fileres'p'. */
1.251     brouard  13145:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13146:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13147: 
                   13148:   fprintf(fichtm,"\n");
1.286     brouard  13149:   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  13150:          ftol, stepm);
                   13151:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13152:   ncurrv=1;
                   13153:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13154:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13155:   ncurrv=i;
                   13156:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13157:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13158:   ncurrv=i;
                   13159:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13160:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13161:   ncurrv=i;
                   13162:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13163:   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", \
                   13164:           nlstate, ndeath, maxwav, mle, weightopt);
                   13165: 
                   13166:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13167: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13168: 
                   13169:   
1.317     brouard  13170:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13171: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13172: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13173:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13174:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13175:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13176:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13177:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13178:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13179: 
1.126     brouard  13180:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13181:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13182:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13183: 
                   13184:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13185:   /* For mortality only */
1.126     brouard  13186:   if (mle==-3){
1.136     brouard  13187:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13188:     for(i=1;i<=NDIM;i++)
                   13189:       for(j=1;j<=NDIM;j++)
                   13190:        ximort[i][j]=0.;
1.186     brouard  13191:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13192:     cens=ivector(firstobs,lastobs);
                   13193:     ageexmed=vector(firstobs,lastobs);
                   13194:     agecens=vector(firstobs,lastobs);
                   13195:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13196:                
1.126     brouard  13197:     for (i=1; i<=imx; i++){
                   13198:       dcwave[i]=-1;
                   13199:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13200:        if (s[m][i]>nlstate) {
                   13201:          dcwave[i]=m;
                   13202:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13203:          break;
                   13204:        }
1.126     brouard  13205:     }
1.226     brouard  13206:     
1.126     brouard  13207:     for (i=1; i<=imx; i++) {
                   13208:       if (wav[i]>0){
1.226     brouard  13209:        ageexmed[i]=agev[mw[1][i]][i];
                   13210:        j=wav[i];
                   13211:        agecens[i]=1.; 
                   13212:        
                   13213:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13214:          agecens[i]=agev[mw[j][i]][i];
                   13215:          cens[i]= 1;
                   13216:        }else if (ageexmed[i]< 1) 
                   13217:          cens[i]= -1;
                   13218:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13219:          cens[i]=0 ;
1.126     brouard  13220:       }
                   13221:       else cens[i]=-1;
                   13222:     }
                   13223:     
                   13224:     for (i=1;i<=NDIM;i++) {
                   13225:       for (j=1;j<=NDIM;j++)
1.226     brouard  13226:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13227:     }
                   13228:     
1.302     brouard  13229:     p[1]=0.0268; p[NDIM]=0.083;
                   13230:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13231:     
                   13232:     
1.136     brouard  13233: #ifdef GSL
                   13234:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13235: #else
1.126     brouard  13236:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13237: #endif
1.201     brouard  13238:     strcpy(filerespow,"POW-MORT_"); 
                   13239:     strcat(filerespow,fileresu);
1.126     brouard  13240:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13241:       printf("Problem with resultfile: %s\n", filerespow);
                   13242:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13243:     }
1.136     brouard  13244: #ifdef GSL
                   13245:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13246: #else
1.126     brouard  13247:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13248: #endif
1.126     brouard  13249:     /*  for (i=1;i<=nlstate;i++)
                   13250:        for(j=1;j<=nlstate+ndeath;j++)
                   13251:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13252:     */
                   13253:     fprintf(ficrespow,"\n");
1.136     brouard  13254: #ifdef GSL
                   13255:     /* gsl starts here */ 
                   13256:     T = gsl_multimin_fminimizer_nmsimplex;
                   13257:     gsl_multimin_fminimizer *sfm = NULL;
                   13258:     gsl_vector *ss, *x;
                   13259:     gsl_multimin_function minex_func;
                   13260: 
                   13261:     /* Initial vertex size vector */
                   13262:     ss = gsl_vector_alloc (NDIM);
                   13263:     
                   13264:     if (ss == NULL){
                   13265:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13266:     }
                   13267:     /* Set all step sizes to 1 */
                   13268:     gsl_vector_set_all (ss, 0.001);
                   13269: 
                   13270:     /* Starting point */
1.126     brouard  13271:     
1.136     brouard  13272:     x = gsl_vector_alloc (NDIM);
                   13273:     
                   13274:     if (x == NULL){
                   13275:       gsl_vector_free(ss);
                   13276:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13277:     }
                   13278:   
                   13279:     /* Initialize method and iterate */
                   13280:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13281:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13282:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13283:     gsl_vector_set(x, 0, p[1]);
                   13284:     gsl_vector_set(x, 1, p[2]);
                   13285: 
                   13286:     minex_func.f = &gompertz_f;
                   13287:     minex_func.n = NDIM;
                   13288:     minex_func.params = (void *)&p; /* ??? */
                   13289:     
                   13290:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13291:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13292:     
                   13293:     printf("Iterations beginning .....\n\n");
                   13294:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13295: 
                   13296:     iteri=0;
                   13297:     while (rval == GSL_CONTINUE){
                   13298:       iteri++;
                   13299:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13300:       
                   13301:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13302:       fflush(0);
                   13303:       
                   13304:       if (status) 
                   13305:         break;
                   13306:       
                   13307:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13308:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13309:       
                   13310:       if (rval == GSL_SUCCESS)
                   13311:         printf ("converged to a local maximum at\n");
                   13312:       
                   13313:       printf("%5d ", iteri);
                   13314:       for (it = 0; it < NDIM; it++){
                   13315:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13316:       }
                   13317:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13318:     }
                   13319:     
                   13320:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13321:     
                   13322:     gsl_vector_free(x); /* initial values */
                   13323:     gsl_vector_free(ss); /* inital step size */
                   13324:     for (it=0; it<NDIM; it++){
                   13325:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13326:       fprintf(ficrespow," %.12lf", p[it]);
                   13327:     }
                   13328:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13329: #endif
                   13330: #ifdef POWELL
                   13331:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13332: #endif  
1.126     brouard  13333:     fclose(ficrespow);
                   13334:     
1.203     brouard  13335:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13336: 
                   13337:     for(i=1; i <=NDIM; i++)
                   13338:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13339:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13340:     
                   13341:     printf("\nCovariance matrix\n ");
1.203     brouard  13342:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13343:     for(i=1; i <=NDIM; i++) {
                   13344:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13345:                                printf("%f ",matcov[i][j]);
                   13346:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13347:       }
1.203     brouard  13348:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13349:     }
                   13350:     
                   13351:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13352:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13353:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13354:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13355:     }
1.302     brouard  13356:     lsurv=vector(agegomp,AGESUP);
                   13357:     lpop=vector(agegomp,AGESUP);
                   13358:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13359:     lsurv[agegomp]=100000;
                   13360:     
                   13361:     for (k=agegomp;k<=AGESUP;k++) {
                   13362:       agemortsup=k;
                   13363:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13364:     }
                   13365:     
                   13366:     for (k=agegomp;k<agemortsup;k++)
                   13367:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13368:     
                   13369:     for (k=agegomp;k<agemortsup;k++){
                   13370:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13371:       sumlpop=sumlpop+lpop[k];
                   13372:     }
                   13373:     
                   13374:     tpop[agegomp]=sumlpop;
                   13375:     for (k=agegomp;k<(agemortsup-3);k++){
                   13376:       /*  tpop[k+1]=2;*/
                   13377:       tpop[k+1]=tpop[k]-lpop[k];
                   13378:     }
                   13379:     
                   13380:     
                   13381:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13382:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13383:       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]);
                   13384:     
                   13385:     
                   13386:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13387:                ageminpar=50;
                   13388:                agemaxpar=100;
1.194     brouard  13389:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13390:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13391: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13392: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13393:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13394: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13395: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13396:     }else{
                   13397:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13398:                        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  13399:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13400:                }
1.201     brouard  13401:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13402:                     stepm, weightopt,\
                   13403:                     model,imx,p,matcov,agemortsup);
                   13404:     
1.302     brouard  13405:     free_vector(lsurv,agegomp,AGESUP);
                   13406:     free_vector(lpop,agegomp,AGESUP);
                   13407:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13408:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13409:     free_ivector(dcwave,firstobs,lastobs);
                   13410:     free_vector(agecens,firstobs,lastobs);
                   13411:     free_vector(ageexmed,firstobs,lastobs);
                   13412:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13413: #ifdef GSL
1.136     brouard  13414: #endif
1.186     brouard  13415:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13416:   /* Standard  */
                   13417:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13418:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13419:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13420:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13421:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13422:     for (k=1; k<=npar;k++)
                   13423:       printf(" %d %8.5f",k,p[k]);
                   13424:     printf("\n");
1.205     brouard  13425:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13426:       /* mlikeli uses func not funcone */
1.247     brouard  13427:       /* for(i=1;i<nlstate;i++){ */
                   13428:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13429:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13430:       /* } */
1.205     brouard  13431:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13432:     }
                   13433:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13434:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13435:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13436:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13437:     }
                   13438:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13439:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13440:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13441:           /* exit(0); */
1.126     brouard  13442:     for (k=1; k<=npar;k++)
                   13443:       printf(" %d %8.5f",k,p[k]);
                   13444:     printf("\n");
                   13445:     
                   13446:     /*--------- results files --------------*/
1.283     brouard  13447:     /* 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  13448:     
                   13449:     
                   13450:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13451:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13452:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13453: 
                   13454:     printf("#model=  1      +     age ");
                   13455:     fprintf(ficres,"#model=  1      +     age ");
                   13456:     fprintf(ficlog,"#model=  1      +     age ");
                   13457:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13458: </ul>", model);
                   13459: 
                   13460:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13461:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13462:     if(nagesqr==1){
                   13463:       printf("  + age*age  ");
                   13464:       fprintf(ficres,"  + age*age  ");
                   13465:       fprintf(ficlog,"  + age*age  ");
                   13466:       fprintf(fichtm, "<th>+ age*age</th>");
                   13467:     }
                   13468:     for(j=1;j <=ncovmodel-2;j++){
                   13469:       if(Typevar[j]==0) {
                   13470:        printf("  +      V%d  ",Tvar[j]);
                   13471:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13472:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13473:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13474:       }else if(Typevar[j]==1) {
                   13475:        printf("  +    V%d*age ",Tvar[j]);
                   13476:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13477:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13478:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13479:       }else if(Typevar[j]==2) {
                   13480:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13481:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13482:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13483:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13484:       }
                   13485:     }
                   13486:     printf("\n");
                   13487:     fprintf(ficres,"\n");
                   13488:     fprintf(ficlog,"\n");
                   13489:     fprintf(fichtm, "</tr>");
                   13490:     fprintf(fichtm, "\n");
                   13491:     
                   13492:     
1.126     brouard  13493:     for(i=1,jk=1; i <=nlstate; i++){
                   13494:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13495:        if (k != i) {
1.319     brouard  13496:          fprintf(fichtm, "<tr>");
1.225     brouard  13497:          printf("%d%d ",i,k);
                   13498:          fprintf(ficlog,"%d%d ",i,k);
                   13499:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13500:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13501:          for(j=1; j <=ncovmodel; j++){
                   13502:            printf("%12.7f ",p[jk]);
                   13503:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13504:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13505:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13506:            jk++; 
                   13507:          }
                   13508:          printf("\n");
                   13509:          fprintf(ficlog,"\n");
                   13510:          fprintf(ficres,"\n");
1.319     brouard  13511:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13512:        }
1.126     brouard  13513:       }
                   13514:     }
1.319     brouard  13515:     /* fprintf(fichtm,"</tr>\n"); */
                   13516:     fprintf(fichtm,"</table>\n");
                   13517:     fprintf(fichtm, "\n");
                   13518: 
1.203     brouard  13519:     if(mle != 0){
                   13520:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13521:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13522:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13523:       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");
                   13524:       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  13525:       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  13526:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13527:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13528:       if(nagesqr==1){
                   13529:        printf("  + age*age  ");
                   13530:        fprintf(ficres,"  + age*age  ");
                   13531:        fprintf(ficlog,"  + age*age  ");
                   13532:        fprintf(fichtm, "<th>+ age*age</th>");
                   13533:       }
                   13534:       for(j=1;j <=ncovmodel-2;j++){
                   13535:        if(Typevar[j]==0) {
                   13536:          printf("  +      V%d  ",Tvar[j]);
                   13537:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13538:        }else if(Typevar[j]==1) {
                   13539:          printf("  +    V%d*age ",Tvar[j]);
                   13540:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13541:        }else if(Typevar[j]==2) {
                   13542:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13543:        }
                   13544:       }
                   13545:       fprintf(fichtm, "</tr>\n");
                   13546:  
1.203     brouard  13547:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13548:        for(k=1; k <=(nlstate+ndeath); k++){
                   13549:          if (k != i) {
1.319     brouard  13550:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13551:            printf("%d%d ",i,k);
                   13552:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13553:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13554:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13555:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13556:              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]));
                   13557:              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  13558:              if(fabs(wald) > 1.96){
1.321     brouard  13559:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13560:              }else{
                   13561:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13562:              }
1.324     brouard  13563:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13564:              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  13565:              jk++; 
                   13566:            }
                   13567:            printf("\n");
                   13568:            fprintf(ficlog,"\n");
1.319     brouard  13569:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13570:          }
                   13571:        }
1.193     brouard  13572:       }
1.203     brouard  13573:     } /* end of hesscov and Wald tests */
1.319     brouard  13574:     fprintf(fichtm,"</table>\n");
1.225     brouard  13575:     
1.203     brouard  13576:     /*  */
1.126     brouard  13577:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13578:     printf("# Scales (for hessian or gradient estimation)\n");
                   13579:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13580:     for(i=1,jk=1; i <=nlstate; i++){
                   13581:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13582:        if (j!=i) {
                   13583:          fprintf(ficres,"%1d%1d",i,j);
                   13584:          printf("%1d%1d",i,j);
                   13585:          fprintf(ficlog,"%1d%1d",i,j);
                   13586:          for(k=1; k<=ncovmodel;k++){
                   13587:            printf(" %.5e",delti[jk]);
                   13588:            fprintf(ficlog," %.5e",delti[jk]);
                   13589:            fprintf(ficres," %.5e",delti[jk]);
                   13590:            jk++;
                   13591:          }
                   13592:          printf("\n");
                   13593:          fprintf(ficlog,"\n");
                   13594:          fprintf(ficres,"\n");
                   13595:        }
1.126     brouard  13596:       }
                   13597:     }
                   13598:     
                   13599:     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  13600:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13601:       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");
                   13602:     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");
                   13603:     /* # 121 Var(a12)\n\ */
                   13604:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13605:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13606:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13607:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13608:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13609:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13610:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13611:     
                   13612:     
                   13613:     /* Just to have a covariance matrix which will be more understandable
                   13614:        even is we still don't want to manage dictionary of variables
                   13615:     */
                   13616:     for(itimes=1;itimes<=2;itimes++){
                   13617:       jj=0;
                   13618:       for(i=1; i <=nlstate; i++){
1.225     brouard  13619:        for(j=1; j <=nlstate+ndeath; j++){
                   13620:          if(j==i) continue;
                   13621:          for(k=1; k<=ncovmodel;k++){
                   13622:            jj++;
                   13623:            ca[0]= k+'a'-1;ca[1]='\0';
                   13624:            if(itimes==1){
                   13625:              if(mle>=1)
                   13626:                printf("#%1d%1d%d",i,j,k);
                   13627:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13628:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13629:            }else{
                   13630:              if(mle>=1)
                   13631:                printf("%1d%1d%d",i,j,k);
                   13632:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13633:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13634:            }
                   13635:            ll=0;
                   13636:            for(li=1;li <=nlstate; li++){
                   13637:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13638:                if(lj==li) continue;
                   13639:                for(lk=1;lk<=ncovmodel;lk++){
                   13640:                  ll++;
                   13641:                  if(ll<=jj){
                   13642:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13643:                    if(ll<jj){
                   13644:                      if(itimes==1){
                   13645:                        if(mle>=1)
                   13646:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13647:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13648:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13649:                      }else{
                   13650:                        if(mle>=1)
                   13651:                          printf(" %.5e",matcov[jj][ll]); 
                   13652:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13653:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13654:                      }
                   13655:                    }else{
                   13656:                      if(itimes==1){
                   13657:                        if(mle>=1)
                   13658:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13659:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13660:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13661:                      }else{
                   13662:                        if(mle>=1)
                   13663:                          printf(" %.7e",matcov[jj][ll]); 
                   13664:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13665:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13666:                      }
                   13667:                    }
                   13668:                  }
                   13669:                } /* end lk */
                   13670:              } /* end lj */
                   13671:            } /* end li */
                   13672:            if(mle>=1)
                   13673:              printf("\n");
                   13674:            fprintf(ficlog,"\n");
                   13675:            fprintf(ficres,"\n");
                   13676:            numlinepar++;
                   13677:          } /* end k*/
                   13678:        } /*end j */
1.126     brouard  13679:       } /* end i */
                   13680:     } /* end itimes */
                   13681:     
                   13682:     fflush(ficlog);
                   13683:     fflush(ficres);
1.225     brouard  13684:     while(fgets(line, MAXLINE, ficpar)) {
                   13685:       /* If line starts with a # it is a comment */
                   13686:       if (line[0] == '#') {
                   13687:        numlinepar++;
                   13688:        fputs(line,stdout);
                   13689:        fputs(line,ficparo);
                   13690:        fputs(line,ficlog);
1.299     brouard  13691:        fputs(line,ficres);
1.225     brouard  13692:        continue;
                   13693:       }else
                   13694:        break;
                   13695:     }
                   13696:     
1.209     brouard  13697:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13698:     /*   ungetc(c,ficpar); */
                   13699:     /*   fgets(line, MAXLINE, ficpar); */
                   13700:     /*   fputs(line,stdout); */
                   13701:     /*   fputs(line,ficparo); */
                   13702:     /* } */
                   13703:     /* ungetc(c,ficpar); */
1.126     brouard  13704:     
                   13705:     estepm=0;
1.209     brouard  13706:     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  13707:       
                   13708:       if (num_filled != 6) {
                   13709:        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);
                   13710:        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);
                   13711:        goto end;
                   13712:       }
                   13713:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13714:     }
                   13715:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13716:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13717:     
1.209     brouard  13718:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13719:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13720:     if (fage <= 2) {
                   13721:       bage = ageminpar;
                   13722:       fage = agemaxpar;
                   13723:     }
                   13724:     
                   13725:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13726:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13727:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13728:                
1.186     brouard  13729:     /* Other stuffs, more or less useful */    
1.254     brouard  13730:     while(fgets(line, MAXLINE, ficpar)) {
                   13731:       /* If line starts with a # it is a comment */
                   13732:       if (line[0] == '#') {
                   13733:        numlinepar++;
                   13734:        fputs(line,stdout);
                   13735:        fputs(line,ficparo);
                   13736:        fputs(line,ficlog);
1.299     brouard  13737:        fputs(line,ficres);
1.254     brouard  13738:        continue;
                   13739:       }else
                   13740:        break;
                   13741:     }
                   13742: 
                   13743:     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){
                   13744:       
                   13745:       if (num_filled != 7) {
                   13746:        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);
                   13747:        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);
                   13748:        goto end;
                   13749:       }
                   13750:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13751:       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);
                   13752:       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);
                   13753:       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  13754:     }
1.254     brouard  13755: 
                   13756:     while(fgets(line, MAXLINE, ficpar)) {
                   13757:       /* If line starts with a # it is a comment */
                   13758:       if (line[0] == '#') {
                   13759:        numlinepar++;
                   13760:        fputs(line,stdout);
                   13761:        fputs(line,ficparo);
                   13762:        fputs(line,ficlog);
1.299     brouard  13763:        fputs(line,ficres);
1.254     brouard  13764:        continue;
                   13765:       }else
                   13766:        break;
1.126     brouard  13767:     }
                   13768:     
                   13769:     
                   13770:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13771:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13772:     
1.254     brouard  13773:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13774:       if (num_filled != 1) {
                   13775:        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);
                   13776:        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);
                   13777:        goto end;
                   13778:       }
                   13779:       printf("pop_based=%d\n",popbased);
                   13780:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13781:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13782:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13783:     }
                   13784:      
1.258     brouard  13785:     /* Results */
1.332     brouard  13786:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13787:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13788:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13789:     endishere=0;
1.258     brouard  13790:     nresult=0;
1.308     brouard  13791:     parameterline=0;
1.258     brouard  13792:     do{
                   13793:       if(!fgets(line, MAXLINE, ficpar)){
                   13794:        endishere=1;
1.308     brouard  13795:        parameterline=15;
1.258     brouard  13796:       }else if (line[0] == '#') {
                   13797:        /* If line starts with a # it is a comment */
1.254     brouard  13798:        numlinepar++;
                   13799:        fputs(line,stdout);
                   13800:        fputs(line,ficparo);
                   13801:        fputs(line,ficlog);
1.299     brouard  13802:        fputs(line,ficres);
1.254     brouard  13803:        continue;
1.258     brouard  13804:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13805:        parameterline=11;
1.296     brouard  13806:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13807:        parameterline=12;
1.307     brouard  13808:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13809:        parameterline=13;
1.307     brouard  13810:       }
1.258     brouard  13811:       else{
                   13812:        parameterline=14;
1.254     brouard  13813:       }
1.308     brouard  13814:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13815:       case 11:
1.296     brouard  13816:        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)){
                   13817:                  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  13818:          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);
                   13819:          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);
                   13820:          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);
                   13821:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13822:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13823:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13824:           prvforecast = 1;
                   13825:        } 
                   13826:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13827:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13828:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13829:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13830:           prvforecast = 2;
                   13831:        }
                   13832:        else {
                   13833:          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);
                   13834:          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);
                   13835:          goto end;
1.258     brouard  13836:        }
1.254     brouard  13837:        break;
1.258     brouard  13838:       case 12:
1.296     brouard  13839:        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)){
                   13840:           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);
                   13841:          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);
                   13842:          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);
                   13843:          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);
                   13844:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13845:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13846:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13847:           prvbackcast = 1;
                   13848:        } 
                   13849:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13850:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13851:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13852:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13853:           prvbackcast = 2;
                   13854:        }
                   13855:        else {
                   13856:          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);
                   13857:          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);
                   13858:          goto end;
1.258     brouard  13859:        }
1.230     brouard  13860:        break;
1.258     brouard  13861:       case 13:
1.332     brouard  13862:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13863:        nresult++; /* Sum of resultlines */
1.342   ! brouard  13864:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  13865:        /* removefirstspace(&resultlineori); */
                   13866:        
                   13867:        if(strstr(resultlineori,"v") !=0){
                   13868:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13869:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13870:          return 1;
                   13871:        }
                   13872:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342   ! brouard  13873:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  13874:        if(nresult > MAXRESULTLINESPONE-1){
                   13875:          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);
                   13876:          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  13877:          goto end;
                   13878:        }
1.332     brouard  13879:        
1.310     brouard  13880:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13881:          fprintf(ficparo,"result: %s\n",resultline);
                   13882:          fprintf(ficres,"result: %s\n",resultline);
                   13883:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13884:        } else
                   13885:          goto end;
1.307     brouard  13886:        break;
                   13887:       case 14:
                   13888:        printf("Error: Unknown command '%s'\n",line);
                   13889:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13890:        if(line[0] == ' ' || line[0] == '\n'){
                   13891:          printf("It should not be an empty line '%s'\n",line);
                   13892:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13893:        }         
1.307     brouard  13894:        if(ncovmodel >=2 && nresult==0 ){
                   13895:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13896:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13897:        }
1.307     brouard  13898:        /* goto end; */
                   13899:        break;
1.308     brouard  13900:       case 15:
                   13901:        printf("End of resultlines.\n");
                   13902:        fprintf(ficlog,"End of resultlines.\n");
                   13903:        break;
                   13904:       default: /* parameterline =0 */
1.307     brouard  13905:        nresult=1;
                   13906:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13907:       } /* End switch parameterline */
                   13908:     }while(endishere==0); /* End do */
1.126     brouard  13909:     
1.230     brouard  13910:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13911:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13912:     
                   13913:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13914:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13915:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13916: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13917: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13918:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13919: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13920: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13921:     }else{
1.270     brouard  13922:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13923:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13924:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13925:       if(prvforecast==1){
                   13926:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13927:         jprojd=jproj1;
                   13928:         mprojd=mproj1;
                   13929:         anprojd=anproj1;
                   13930:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13931:         jprojf=jproj2;
                   13932:         mprojf=mproj2;
                   13933:         anprojf=anproj2;
                   13934:       } else if(prvforecast == 2){
                   13935:         dateprojd=dateintmean;
                   13936:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13937:         dateprojf=dateintmean+yrfproj;
                   13938:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13939:       }
                   13940:       if(prvbackcast==1){
                   13941:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13942:         jbackd=jback1;
                   13943:         mbackd=mback1;
                   13944:         anbackd=anback1;
                   13945:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13946:         jbackf=jback2;
                   13947:         mbackf=mback2;
                   13948:         anbackf=anback2;
                   13949:       } else if(prvbackcast == 2){
                   13950:         datebackd=dateintmean;
                   13951:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13952:         datebackf=dateintmean-yrbproj;
                   13953:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13954:       }
                   13955:       
                   13956:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13957:     }
                   13958:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13959:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13960:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13961:                
1.225     brouard  13962:     /*------------ free_vector  -------------*/
                   13963:     /*  chdir(path); */
1.220     brouard  13964:                
1.215     brouard  13965:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13966:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13967:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13968:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13969:     free_lvector(num,firstobs,lastobs);
                   13970:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13971:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13972:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13973:     fclose(ficparo);
                   13974:     fclose(ficres);
1.220     brouard  13975:                
                   13976:                
1.186     brouard  13977:     /* Other results (useful)*/
1.220     brouard  13978:                
                   13979:                
1.126     brouard  13980:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13981:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13982:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13983:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13984:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13985:     fclose(ficrespl);
                   13986: 
                   13987:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13988:     /*#include "hpijx.h"*/
1.332     brouard  13989:     /** 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?*/
                   13990:     /* calls hpxij with combination k */
1.180     brouard  13991:     hPijx(p, bage, fage);
1.145     brouard  13992:     fclose(ficrespij);
1.227     brouard  13993:     
1.220     brouard  13994:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13995:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13996:     k=1;
1.126     brouard  13997:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13998:     
1.269     brouard  13999:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14000:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14001:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14002:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14003:        for(k=1;k<=ncovcombmax;k++)
                   14004:          probs[i][j][k]=0.;
1.269     brouard  14005:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14006:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14007:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14008:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14009:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14010:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14011:          for(k=1;k<=ncovcombmax;k++)
                   14012:            mobaverages[i][j][k]=0.;
1.219     brouard  14013:       mobaverage=mobaverages;
                   14014:       if (mobilav!=0) {
1.235     brouard  14015:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14016:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14017:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14018:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14019:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14020:        }
1.269     brouard  14021:       } else if (mobilavproj !=0) {
1.235     brouard  14022:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14023:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14024:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14025:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14026:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14027:        }
1.269     brouard  14028:       }else{
                   14029:        printf("Internal error moving average\n");
                   14030:        fflush(stdout);
                   14031:        exit(1);
1.219     brouard  14032:       }
                   14033:     }/* end if moving average */
1.227     brouard  14034:     
1.126     brouard  14035:     /*---------- Forecasting ------------------*/
1.296     brouard  14036:     if(prevfcast==1){ 
                   14037:       /*   /\*    if(stepm ==1){*\/ */
                   14038:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14039:       /*This done previously after freqsummary.*/
                   14040:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14041:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14042:       
                   14043:       /* } else if (prvforecast==2){ */
                   14044:       /*   /\*    if(stepm ==1){*\/ */
                   14045:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14046:       /* } */
                   14047:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14048:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14049:     }
1.269     brouard  14050: 
1.296     brouard  14051:     /* Prevbcasting */
                   14052:     if(prevbcast==1){
1.219     brouard  14053:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14054:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14055:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14056: 
                   14057:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14058: 
                   14059:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14060: 
1.219     brouard  14061:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14062:       fclose(ficresplb);
                   14063: 
1.222     brouard  14064:       hBijx(p, bage, fage, mobaverage);
                   14065:       fclose(ficrespijb);
1.219     brouard  14066: 
1.296     brouard  14067:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14068:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14069:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14070:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14071:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14072:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14073: 
                   14074:       
1.269     brouard  14075:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14076: 
                   14077:       
1.269     brouard  14078:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14079:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14080:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14081:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14082:     }    /* end  Prevbcasting */
1.268     brouard  14083:  
1.186     brouard  14084:  
                   14085:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14086: 
1.215     brouard  14087:     free_ivector(wav,1,imx);
                   14088:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14089:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14090:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14091:                
                   14092:                
1.127     brouard  14093:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14094:                
1.201     brouard  14095:     strcpy(filerese,"E_");
                   14096:     strcat(filerese,fileresu);
1.126     brouard  14097:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14098:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14099:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14100:     }
1.208     brouard  14101:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14102:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14103: 
                   14104:     pstamp(ficreseij);
1.219     brouard  14105:                
1.235     brouard  14106:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14107:     if (cptcovn < 1){i1=1;}
                   14108:     
                   14109:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14110:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14111:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14112:        continue;
1.219     brouard  14113:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14114:       printf("\n#****** ");
1.225     brouard  14115:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14116:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14117:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14118:       }
                   14119:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14120:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14121:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14122:       }
                   14123:       fprintf(ficreseij,"******\n");
1.235     brouard  14124:       printf("******\n");
1.219     brouard  14125:       
                   14126:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14127:       oldm=oldms;savm=savms;
1.330     brouard  14128:       /* 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  14129:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14130:       
1.219     brouard  14131:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14132:     }
                   14133:     fclose(ficreseij);
1.208     brouard  14134:     printf("done evsij\n");fflush(stdout);
                   14135:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14136: 
1.218     brouard  14137:                
1.227     brouard  14138:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14139:     /* Should be moved in a function */                
1.201     brouard  14140:     strcpy(filerest,"T_");
                   14141:     strcat(filerest,fileresu);
1.127     brouard  14142:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14143:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14144:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14145:     }
1.208     brouard  14146:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14147:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14148:     strcpy(fileresstde,"STDE_");
                   14149:     strcat(fileresstde,fileresu);
1.126     brouard  14150:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14151:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14152:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14153:     }
1.227     brouard  14154:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14155:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14156: 
1.201     brouard  14157:     strcpy(filerescve,"CVE_");
                   14158:     strcat(filerescve,fileresu);
1.126     brouard  14159:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14160:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14161:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14162:     }
1.227     brouard  14163:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14164:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14165: 
1.201     brouard  14166:     strcpy(fileresv,"V_");
                   14167:     strcat(fileresv,fileresu);
1.126     brouard  14168:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14169:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14170:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14171:     }
1.227     brouard  14172:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14173:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14174: 
1.235     brouard  14175:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14176:     if (cptcovn < 1){i1=1;}
                   14177:     
1.334     brouard  14178:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14179:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14180:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14181:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14182:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14183:       /* */
                   14184:       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  14185:        continue;
1.321     brouard  14186:       printf("\n# model %s \n#****** Result for:", model);
                   14187:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14188:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14189:       /* It might not be a good idea to mix dummies and quantitative */
                   14190:       /* 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 *\/ */
                   14191:       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 */
                   14192:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14193:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14194:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14195:         * (V5 is quanti) V4 and V3 are dummies
                   14196:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14197:         *                                                              l=1 l=2
                   14198:         *                                                           k=1  1   1   0   0
                   14199:         *                                                           k=2  2   1   1   0
                   14200:         *                                                           k=3 [1] [2]  0   1
                   14201:         *                                                           k=4  2   2   1   1
                   14202:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14203:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14204:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14205:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14206:         */
                   14207:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14208:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14209: /* We give up with the combinations!! */
1.342   ! brouard  14210:        /* if(debugILK) */
        !          14211:        /*   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  14212: 
                   14213:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.337     brouard  14214:          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  */
                   14215:          fprintf(ficlog,"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  */
                   14216:          fprintf(ficrest,"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  */
1.334     brouard  14217:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14218:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14219:          }else{
                   14220:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14221:          }
                   14222:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14223:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14224:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14225:          /* For each selected (single) quantitative value */
1.337     brouard  14226:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14227:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14228:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14229:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14230:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14231:          }else{
                   14232:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14233:          }
                   14234:        }else{
                   14235:          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 */
                   14236:          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 */
                   14237:          exit(1);
                   14238:        }
1.335     brouard  14239:       } /* End loop for each variable in the resultline */
1.334     brouard  14240:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14241:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14242:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14243:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14244:       /* }      */
1.208     brouard  14245:       fprintf(ficrest,"******\n");
1.227     brouard  14246:       fprintf(ficlog,"******\n");
                   14247:       printf("******\n");
1.208     brouard  14248:       
                   14249:       fprintf(ficresstdeij,"\n#****** ");
                   14250:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14251:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14252:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14253:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14254:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14255:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14256:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14257:       }
                   14258:       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  14259:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14260:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14261:       }        
1.208     brouard  14262:       fprintf(ficresstdeij,"******\n");
                   14263:       fprintf(ficrescveij,"******\n");
                   14264:       
                   14265:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14266:       /* pstamp(ficresvij); */
1.225     brouard  14267:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14268:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14269:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14270:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14271:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14272:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14273:       }        
1.208     brouard  14274:       fprintf(ficresvij,"******\n");
                   14275:       
                   14276:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14277:       oldm=oldms;savm=savms;
1.235     brouard  14278:       printf(" cvevsij ");
                   14279:       fprintf(ficlog, " cvevsij ");
                   14280:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14281:       printf(" end cvevsij \n ");
                   14282:       fprintf(ficlog, " end cvevsij \n ");
                   14283:       
                   14284:       /*
                   14285:        */
                   14286:       /* goto endfree; */
                   14287:       
                   14288:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14289:       pstamp(ficrest);
                   14290:       
1.269     brouard  14291:       epj=vector(1,nlstate+1);
1.208     brouard  14292:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14293:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14294:        cptcod= 0; /* To be deleted */
                   14295:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14296:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14297:        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  14298:        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 ");
                   14299:        if(vpopbased==1)
                   14300:          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);
                   14301:        else
1.288     brouard  14302:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14303:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14304:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14305:        fprintf(ficrest,"\n");
                   14306:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14307:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14308:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14309:        for(age=bage; age <=fage ;age++){
1.235     brouard  14310:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14311:          if (vpopbased==1) {
                   14312:            if(mobilav ==0){
                   14313:              for(i=1; i<=nlstate;i++)
                   14314:                prlim[i][i]=probs[(int)age][i][k];
                   14315:            }else{ /* mobilav */ 
                   14316:              for(i=1; i<=nlstate;i++)
                   14317:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14318:            }
                   14319:          }
1.219     brouard  14320:          
1.227     brouard  14321:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14322:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14323:          /* printf(" age %4.0f ",age); */
                   14324:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14325:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14326:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14327:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14328:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14329:            }
                   14330:            epj[nlstate+1] +=epj[j];
                   14331:          }
                   14332:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14333:          
1.227     brouard  14334:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14335:            for(j=1;j <=nlstate;j++)
                   14336:              vepp += vareij[i][j][(int)age];
                   14337:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14338:          for(j=1;j <=nlstate;j++){
                   14339:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14340:          }
                   14341:          fprintf(ficrest,"\n");
                   14342:        }
1.208     brouard  14343:       } /* End vpopbased */
1.269     brouard  14344:       free_vector(epj,1,nlstate+1);
1.208     brouard  14345:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14346:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14347:       printf("done selection\n");fflush(stdout);
                   14348:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14349:       
1.335     brouard  14350:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14351: 
                   14352:     printf("done State-specific expectancies\n");fflush(stdout);
                   14353:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14354: 
1.335     brouard  14355:     /* variance-covariance of forward period prevalence */
1.269     brouard  14356:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14357: 
1.227     brouard  14358:     
1.290     brouard  14359:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14360:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14361:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14362:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14363:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14364:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14365:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14366:     free_ivector(tab,1,NCOVMAX);
                   14367:     fclose(ficresstdeij);
                   14368:     fclose(ficrescveij);
                   14369:     fclose(ficresvij);
                   14370:     fclose(ficrest);
                   14371:     fclose(ficpar);
                   14372:     
                   14373:     
1.126     brouard  14374:     /*---------- End : free ----------------*/
1.219     brouard  14375:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14376:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14377:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14378:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14379:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14380:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14381:   /* endfree:*/
                   14382:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14383:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14384:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  14385:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   14386:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14387:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14388:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14389:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14390:   free_matrix(matcov,1,npar,1,npar);
                   14391:   free_matrix(hess,1,npar,1,npar);
                   14392:   /*free_vector(delti,1,npar);*/
                   14393:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14394:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14395:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14396:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14397:   
                   14398:   free_ivector(ncodemax,1,NCOVMAX);
                   14399:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14400:   free_ivector(Dummy,-1,NCOVMAX);
                   14401:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14402:   free_ivector(DummyV,1,NCOVMAX);
                   14403:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14404:   free_ivector(Typevar,-1,NCOVMAX);
                   14405:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14406:   free_ivector(TvarsQ,1,NCOVMAX);
                   14407:   free_ivector(TvarsQind,1,NCOVMAX);
                   14408:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14409:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14410:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14411:   free_ivector(TvarFD,1,NCOVMAX);
                   14412:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14413:   free_ivector(TvarF,1,NCOVMAX);
                   14414:   free_ivector(TvarFind,1,NCOVMAX);
                   14415:   free_ivector(TvarV,1,NCOVMAX);
                   14416:   free_ivector(TvarVind,1,NCOVMAX);
                   14417:   free_ivector(TvarA,1,NCOVMAX);
                   14418:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14419:   free_ivector(TvarFQ,1,NCOVMAX);
                   14420:   free_ivector(TvarFQind,1,NCOVMAX);
                   14421:   free_ivector(TvarVD,1,NCOVMAX);
                   14422:   free_ivector(TvarVDind,1,NCOVMAX);
                   14423:   free_ivector(TvarVQ,1,NCOVMAX);
                   14424:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14425:   free_ivector(TvarVV,1,NCOVMAX);
                   14426:   free_ivector(TvarVVind,1,NCOVMAX);
                   14427:   
1.230     brouard  14428:   free_ivector(Tvarsel,1,NCOVMAX);
                   14429:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14430:   free_ivector(Tposprod,1,NCOVMAX);
                   14431:   free_ivector(Tprod,1,NCOVMAX);
                   14432:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14433:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14434:   free_ivector(Tage,1,NCOVMAX);
                   14435:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14436:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14437:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14438: 
                   14439:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14440: 
1.227     brouard  14441:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14442:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14443:   fflush(fichtm);
                   14444:   fflush(ficgp);
                   14445:   
1.227     brouard  14446:   
1.126     brouard  14447:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14448:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14449:     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  14450:   }else{
                   14451:     printf("End of Imach\n");
                   14452:     fprintf(ficlog,"End of Imach\n");
                   14453:   }
                   14454:   printf("See log file on %s\n",filelog);
                   14455:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14456:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14457:   rend_time = time(NULL);  
                   14458:   end_time = *localtime(&rend_time);
                   14459:   /* tml = *localtime(&end_time.tm_sec); */
                   14460:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14461:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14462:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14463:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14464:   
1.157     brouard  14465:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14466:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14467:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14468:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14469: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14470:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14471:   fclose(fichtm);
                   14472:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14473:   fclose(fichtmcov);
                   14474:   fclose(ficgp);
                   14475:   fclose(ficlog);
                   14476:   /*------ End -----------*/
1.227     brouard  14477:   
1.281     brouard  14478: 
                   14479: /* Executes gnuplot */
1.227     brouard  14480:   
                   14481:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14482: #ifdef WIN32
1.227     brouard  14483:   if (_chdir(pathcd) != 0)
                   14484:     printf("Can't move to directory %s!\n",path);
                   14485:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14486: #else
1.227     brouard  14487:     if(chdir(pathcd) != 0)
                   14488:       printf("Can't move to directory %s!\n", path);
                   14489:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14490: #endif 
1.126     brouard  14491:     printf("Current directory %s!\n",pathcd);
                   14492:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14493:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14494: #ifdef _WIN32
1.126     brouard  14495:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14496: #endif
                   14497:   if(!stat(plotcmd,&info)){
1.158     brouard  14498:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14499:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14500:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14501:     }else
                   14502:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14503: #ifdef __unix
1.126     brouard  14504:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14505:     if(!stat(plotcmd,&info)){
1.158     brouard  14506:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14507:     }else
                   14508:       strcpy(pplotcmd,plotcmd);
                   14509: #endif
                   14510:   }else
                   14511:     strcpy(pplotcmd,plotcmd);
                   14512:   
                   14513:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14514:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14515:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14516:   
1.126     brouard  14517:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14518:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14519:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14520:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14521:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14522:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14523:       strcpy(plotcmd,pplotcmd);
                   14524:     }
1.126     brouard  14525:   }
1.158     brouard  14526:   printf(" Successful, please wait...");
1.126     brouard  14527:   while (z[0] != 'q') {
                   14528:     /* chdir(path); */
1.154     brouard  14529:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14530:     scanf("%s",z);
                   14531: /*     if (z[0] == 'c') system("./imach"); */
                   14532:     if (z[0] == 'e') {
1.158     brouard  14533: #ifdef __APPLE__
1.152     brouard  14534:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14535: #elif __linux
                   14536:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14537: #else
1.152     brouard  14538:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14539: #endif
                   14540:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14541:       system(pplotcmd);
1.126     brouard  14542:     }
                   14543:     else if (z[0] == 'g') system(plotcmd);
                   14544:     else if (z[0] == 'q') exit(0);
                   14545:   }
1.227     brouard  14546: end:
1.126     brouard  14547:   while (z[0] != 'q') {
1.195     brouard  14548:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14549:     scanf("%s",z);
                   14550:   }
1.283     brouard  14551:   printf("End\n");
1.282     brouard  14552:   exit(0);
1.126     brouard  14553: }

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