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

1.363   ! brouard     1: /* $Id: imach.c,v 1.362 2024/06/28 08:00:31 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.360     brouard     3:   $Log: imach.c,v $
1.363   ! brouard     4:   Revision 1.362  2024/06/28 08:00:31  brouard
        !             5:   Summary: 0.99s6
        !             6: 
        !             7:   * imach.c (Module): s6 errors with age*age (harmless).
        !             8: 
1.362     brouard     9:   Revision 1.361  2024/05/12 20:29:32  brouard
                     10:   Summary: Version 0.99s5
                     11: 
                     12:   * src/imach.c Version 0.99s5 In fact, the covariance of total life
                     13:   expectancy e.. with a partial life expectancy e.j is high,
                     14:   therefore the complete matrix of variance covariance has to be
                     15:   included in the formula of the standard error of the proportion of
                     16:   total life expectancy spent in a specific state:
                     17:   var(X/Y)=mu_x^2/mu_y^2*(sigma_x^2/mu_x^2 -2
                     18:   sigma_xy/mu_x/mu_y+sigma^2/mu_y^2).  Also an error with mle=-3
                     19:   made the program core dump. It is fixed in this version.
                     20: 
1.361     brouard    21:   Revision 1.360  2024/04/30 10:59:22  brouard
                     22:   Summary: Version 0.99s4 and estimation of std of e.j/e..
                     23: 
1.360     brouard    24:   Revision 1.359  2024/04/24 21:21:17  brouard
                     25:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
                     26: 
1.359     brouard    27:   Revision 1.6  2024/04/24 21:10:29  brouard
                     28:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
1.358     brouard    29: 
1.359     brouard    30:   Revision 1.5  2023/10/09 09:10:01  brouard
                     31:   Summary: trying to reconsider
1.357     brouard    32: 
1.359     brouard    33:   Revision 1.4  2023/06/22 12:50:51  brouard
                     34:   Summary: stil on going
1.357     brouard    35: 
1.359     brouard    36:   Revision 1.3  2023/06/22 11:28:07  brouard
                     37:   *** empty log message ***
1.356     brouard    38: 
1.359     brouard    39:   Revision 1.2  2023/06/22 11:22:40  brouard
                     40:   Summary: with svd but not working yet
1.355     brouard    41: 
1.354     brouard    42:   Revision 1.353  2023/05/08 18:48:22  brouard
                     43:   *** empty log message ***
                     44: 
1.353     brouard    45:   Revision 1.352  2023/04/29 10:46:21  brouard
                     46:   *** empty log message ***
                     47: 
1.352     brouard    48:   Revision 1.351  2023/04/29 10:43:47  brouard
                     49:   Summary: 099r45
                     50: 
1.351     brouard    51:   Revision 1.350  2023/04/24 11:38:06  brouard
                     52:   *** empty log message ***
                     53: 
1.350     brouard    54:   Revision 1.349  2023/01/31 09:19:37  brouard
                     55:   Summary: Improvements in models with age*Vn*Vm
                     56: 
1.348     brouard    57:   Revision 1.347  2022/09/18 14:36:44  brouard
                     58:   Summary: version 0.99r42
                     59: 
1.347     brouard    60:   Revision 1.346  2022/09/16 13:52:36  brouard
                     61:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     62: 
1.346     brouard    63:   Revision 1.345  2022/09/16 13:40:11  brouard
                     64:   Summary: Version 0.99r41
                     65: 
                     66:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     67: 
1.345     brouard    68:   Revision 1.344  2022/09/14 19:33:30  brouard
                     69:   Summary: version 0.99r40
                     70: 
                     71:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     72: 
1.344     brouard    73:   Revision 1.343  2022/09/14 14:22:16  brouard
                     74:   Summary: version 0.99r39
                     75: 
                     76:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     77:   (fixed or time varying), using new last columns of
                     78:   ILK_parameter.txt file.
                     79: 
1.343     brouard    80:   Revision 1.342  2022/09/11 19:54:09  brouard
                     81:   Summary: 0.99r38
                     82: 
                     83:   * imach.c (Module): Adding timevarying products of any kinds,
                     84:   should work before shifting cotvar from ncovcol+nqv columns in
                     85:   order to have a correspondance between the column of cotvar and
                     86:   the id of column.
                     87:   (Module): Some cleaning and adding covariates in ILK.txt
                     88: 
1.342     brouard    89:   Revision 1.341  2022/09/11 07:58:42  brouard
                     90:   Summary: Version 0.99r38
                     91: 
                     92:   After adding change in cotvar.
                     93: 
1.341     brouard    94:   Revision 1.340  2022/09/11 07:53:11  brouard
                     95:   Summary: Version imach 0.99r37
                     96: 
                     97:   * imach.c (Module): Adding timevarying products of any kinds,
                     98:   should work before shifting cotvar from ncovcol+nqv columns in
                     99:   order to have a correspondance between the column of cotvar and
                    100:   the id of column.
                    101: 
1.340     brouard   102:   Revision 1.339  2022/09/09 17:55:22  brouard
                    103:   Summary: version 0.99r37
                    104: 
                    105:   * imach.c (Module): Many improvements for fixing products of fixed
                    106:   timevarying as well as fixed * fixed, and test with quantitative
                    107:   covariate.
                    108: 
1.339     brouard   109:   Revision 1.338  2022/09/04 17:40:33  brouard
                    110:   Summary: 0.99r36
                    111: 
                    112:   * imach.c (Module): Now the easy runs i.e. without result or
                    113:   model=1+age only did not work. The defautl combination should be 1
                    114:   and not 0 because everything hasn't been tranformed yet.
                    115: 
1.338     brouard   116:   Revision 1.337  2022/09/02 14:26:02  brouard
                    117:   Summary: version 0.99r35
                    118: 
                    119:   * src/imach.c: Version 0.99r35 because it outputs same results with
                    120:   1+age+V1+V1*age for females and 1+age for females only
                    121:   (education=1 noweight)
                    122: 
1.337     brouard   123:   Revision 1.336  2022/08/31 09:52:36  brouard
                    124:   *** empty log message ***
                    125: 
1.336     brouard   126:   Revision 1.335  2022/08/31 08:23:16  brouard
                    127:   Summary: improvements...
                    128: 
1.335     brouard   129:   Revision 1.334  2022/08/25 09:08:41  brouard
                    130:   Summary: In progress for quantitative
                    131: 
1.334     brouard   132:   Revision 1.333  2022/08/21 09:10:30  brouard
                    133:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    134:   reassigning covariates: my first idea was that people will always
                    135:   use the first covariate V1 into the model but in fact they are
                    136:   producing data with many covariates and can use an equation model
                    137:   with some of the covariate; it means that in a model V2+V3 instead
                    138:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    139:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    140:   the equation model is restricted to two variables only (V2, V3)
                    141:   and the combination for V2 should be codtabm(k,1) instead of
                    142:   (codtabm(k,2), and the code should be
                    143:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    144:   made. All of these should be simplified once a day like we did in
                    145:   hpxij() for example by using precov[nres] which is computed in
                    146:   decoderesult for each nres of each resultline. Loop should be done
                    147:   on the equation model globally by distinguishing only product with
                    148:   age (which are changing with age) and no more on type of
                    149:   covariates, single dummies, single covariates.
                    150: 
1.333     brouard   151:   Revision 1.332  2022/08/21 09:06:25  brouard
                    152:   Summary: Version 0.99r33
                    153: 
                    154:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    155:   reassigning covariates: my first idea was that people will always
                    156:   use the first covariate V1 into the model but in fact they are
                    157:   producing data with many covariates and can use an equation model
                    158:   with some of the covariate; it means that in a model V2+V3 instead
                    159:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    160:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    161:   the equation model is restricted to two variables only (V2, V3)
                    162:   and the combination for V2 should be codtabm(k,1) instead of
                    163:   (codtabm(k,2), and the code should be
                    164:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    165:   made. All of these should be simplified once a day like we did in
                    166:   hpxij() for example by using precov[nres] which is computed in
                    167:   decoderesult for each nres of each resultline. Loop should be done
                    168:   on the equation model globally by distinguishing only product with
                    169:   age (which are changing with age) and no more on type of
                    170:   covariates, single dummies, single covariates.
                    171: 
1.332     brouard   172:   Revision 1.331  2022/08/07 05:40:09  brouard
                    173:   *** empty log message ***
                    174: 
1.331     brouard   175:   Revision 1.330  2022/08/06 07:18:25  brouard
                    176:   Summary: last 0.99r31
                    177: 
                    178:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    179: 
1.330     brouard   180:   Revision 1.329  2022/08/03 17:29:54  brouard
                    181:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    182: 
1.329     brouard   183:   Revision 1.328  2022/07/27 17:40:48  brouard
                    184:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    185: 
1.328     brouard   186:   Revision 1.327  2022/07/27 14:47:35  brouard
                    187:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    188: 
1.327     brouard   189:   Revision 1.326  2022/07/26 17:33:55  brouard
                    190:   Summary: some test with nres=1
                    191: 
1.326     brouard   192:   Revision 1.325  2022/07/25 14:27:23  brouard
                    193:   Summary: r30
                    194: 
                    195:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    196:   coredumped, revealed by Feiuno, thank you.
                    197: 
1.325     brouard   198:   Revision 1.324  2022/07/23 17:44:26  brouard
                    199:   *** empty log message ***
                    200: 
1.324     brouard   201:   Revision 1.323  2022/07/22 12:30:08  brouard
                    202:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    203: 
1.323     brouard   204:   Revision 1.322  2022/07/22 12:27:48  brouard
                    205:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    206: 
1.322     brouard   207:   Revision 1.321  2022/07/22 12:04:24  brouard
                    208:   Summary: r28
                    209: 
                    210:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    211: 
1.321     brouard   212:   Revision 1.320  2022/06/02 05:10:11  brouard
                    213:   *** empty log message ***
                    214: 
1.320     brouard   215:   Revision 1.319  2022/06/02 04:45:11  brouard
                    216:   * imach.c (Module): Adding the Wald tests from the log to the main
                    217:   htm for better display of the maximum likelihood estimators.
                    218: 
1.319     brouard   219:   Revision 1.318  2022/05/24 08:10:59  brouard
                    220:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    221:   of confidencce intervals with product in the equation modelC
                    222: 
1.318     brouard   223:   Revision 1.317  2022/05/15 15:06:23  brouard
                    224:   * imach.c (Module):  Some minor improvements
                    225: 
1.317     brouard   226:   Revision 1.316  2022/05/11 15:11:31  brouard
                    227:   Summary: r27
                    228: 
1.316     brouard   229:   Revision 1.315  2022/05/11 15:06:32  brouard
                    230:   *** empty log message ***
                    231: 
1.315     brouard   232:   Revision 1.314  2022/04/13 17:43:09  brouard
                    233:   * imach.c (Module): Adding link to text data files
                    234: 
1.314     brouard   235:   Revision 1.313  2022/04/11 15:57:42  brouard
                    236:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    237: 
1.313     brouard   238:   Revision 1.312  2022/04/05 21:24:39  brouard
                    239:   *** empty log message ***
                    240: 
1.312     brouard   241:   Revision 1.311  2022/04/05 21:03:51  brouard
                    242:   Summary: Fixed quantitative covariates
                    243: 
                    244:          Fixed covariates (dummy or quantitative)
                    245:        with missing values have never been allowed but are ERRORS and
                    246:        program quits. Standard deviations of fixed covariates were
                    247:        wrongly computed. Mean and standard deviations of time varying
                    248:        covariates are still not computed.
                    249: 
1.311     brouard   250:   Revision 1.310  2022/03/17 08:45:53  brouard
                    251:   Summary: 99r25
                    252: 
                    253:   Improving detection of errors: result lines should be compatible with
                    254:   the model.
                    255: 
1.310     brouard   256:   Revision 1.309  2021/05/20 12:39:14  brouard
                    257:   Summary: Version 0.99r24
                    258: 
1.309     brouard   259:   Revision 1.308  2021/03/31 13:11:57  brouard
                    260:   Summary: Version 0.99r23
                    261: 
                    262: 
                    263:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    264: 
1.308     brouard   265:   Revision 1.307  2021/03/08 18:11:32  brouard
                    266:   Summary: 0.99r22 fixed bug on result:
                    267: 
1.307     brouard   268:   Revision 1.306  2021/02/20 15:44:02  brouard
                    269:   Summary: Version 0.99r21
                    270: 
                    271:   * imach.c (Module): Fix bug on quitting after result lines!
                    272:   (Module): Version 0.99r21
                    273: 
1.306     brouard   274:   Revision 1.305  2021/02/20 15:28:30  brouard
                    275:   * imach.c (Module): Fix bug on quitting after result lines!
                    276: 
1.305     brouard   277:   Revision 1.304  2021/02/12 11:34:20  brouard
                    278:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    279: 
1.304     brouard   280:   Revision 1.303  2021/02/11 19:50:15  brouard
                    281:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    282: 
1.303     brouard   283:   Revision 1.302  2020/02/22 21:00:05  brouard
                    284:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    285:   and life table from the data without any state)
                    286: 
1.302     brouard   287:   Revision 1.301  2019/06/04 13:51:20  brouard
                    288:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    289: 
1.301     brouard   290:   Revision 1.300  2019/05/22 19:09:45  brouard
                    291:   Summary: version 0.99r19 of May 2019
                    292: 
1.300     brouard   293:   Revision 1.299  2019/05/22 18:37:08  brouard
                    294:   Summary: Cleaned 0.99r19
                    295: 
1.299     brouard   296:   Revision 1.298  2019/05/22 18:19:56  brouard
                    297:   *** empty log message ***
                    298: 
1.298     brouard   299:   Revision 1.297  2019/05/22 17:56:10  brouard
                    300:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    301: 
1.297     brouard   302:   Revision 1.296  2019/05/20 13:03:18  brouard
                    303:   Summary: Projection syntax simplified
                    304: 
                    305: 
                    306:   We can now start projections, forward or backward, from the mean date
                    307:   of inteviews up to or down to a number of years of projection:
                    308:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    309:   or
                    310:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    311:   or
                    312:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    313:   or
                    314:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    315: 
1.296     brouard   316:   Revision 1.295  2019/05/18 09:52:50  brouard
                    317:   Summary: doxygen tex bug
                    318: 
1.295     brouard   319:   Revision 1.294  2019/05/16 14:54:33  brouard
                    320:   Summary: There was some wrong lines added
                    321: 
1.294     brouard   322:   Revision 1.293  2019/05/09 15:17:34  brouard
                    323:   *** empty log message ***
                    324: 
1.293     brouard   325:   Revision 1.292  2019/05/09 14:17:20  brouard
                    326:   Summary: Some updates
                    327: 
1.292     brouard   328:   Revision 1.291  2019/05/09 13:44:18  brouard
                    329:   Summary: Before ncovmax
                    330: 
1.291     brouard   331:   Revision 1.290  2019/05/09 13:39:37  brouard
                    332:   Summary: 0.99r18 unlimited number of individuals
                    333: 
                    334:   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.
                    335: 
1.290     brouard   336:   Revision 1.289  2018/12/13 09:16:26  brouard
                    337:   Summary: Bug for young ages (<-30) will be in r17
                    338: 
1.289     brouard   339:   Revision 1.288  2018/05/02 20:58:27  brouard
                    340:   Summary: Some bugs fixed
                    341: 
1.288     brouard   342:   Revision 1.287  2018/05/01 17:57:25  brouard
                    343:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    344: 
1.287     brouard   345:   Revision 1.286  2018/04/27 14:27:04  brouard
                    346:   Summary: some minor bugs
                    347: 
1.286     brouard   348:   Revision 1.285  2018/04/21 21:02:16  brouard
                    349:   Summary: Some bugs fixed, valgrind tested
                    350: 
1.285     brouard   351:   Revision 1.284  2018/04/20 05:22:13  brouard
                    352:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    353: 
1.284     brouard   354:   Revision 1.283  2018/04/19 14:49:16  brouard
                    355:   Summary: Some minor bugs fixed
                    356: 
1.283     brouard   357:   Revision 1.282  2018/02/27 22:50:02  brouard
                    358:   *** empty log message ***
                    359: 
1.282     brouard   360:   Revision 1.281  2018/02/27 19:25:23  brouard
                    361:   Summary: Adding second argument for quitting
                    362: 
1.281     brouard   363:   Revision 1.280  2018/02/21 07:58:13  brouard
                    364:   Summary: 0.99r15
                    365: 
                    366:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    367: 
1.280     brouard   368:   Revision 1.279  2017/07/20 13:35:01  brouard
                    369:   Summary: temporary working
                    370: 
1.279     brouard   371:   Revision 1.278  2017/07/19 14:09:02  brouard
                    372:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    373: 
1.278     brouard   374:   Revision 1.277  2017/07/17 08:53:49  brouard
                    375:   Summary: BOM files can be read now
                    376: 
1.277     brouard   377:   Revision 1.276  2017/06/30 15:48:31  brouard
                    378:   Summary: Graphs improvements
                    379: 
1.276     brouard   380:   Revision 1.275  2017/06/30 13:39:33  brouard
                    381:   Summary: Saito's color
                    382: 
1.275     brouard   383:   Revision 1.274  2017/06/29 09:47:08  brouard
                    384:   Summary: Version 0.99r14
                    385: 
1.274     brouard   386:   Revision 1.273  2017/06/27 11:06:02  brouard
                    387:   Summary: More documentation on projections
                    388: 
1.273     brouard   389:   Revision 1.272  2017/06/27 10:22:40  brouard
                    390:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    391: 
1.272     brouard   392:   Revision 1.271  2017/06/27 10:17:50  brouard
                    393:   Summary: Some bug with rint
                    394: 
1.271     brouard   395:   Revision 1.270  2017/05/24 05:45:29  brouard
                    396:   *** empty log message ***
                    397: 
1.270     brouard   398:   Revision 1.269  2017/05/23 08:39:25  brouard
                    399:   Summary: Code into subroutine, cleanings
                    400: 
1.269     brouard   401:   Revision 1.268  2017/05/18 20:09:32  brouard
                    402:   Summary: backprojection and confidence intervals of backprevalence
                    403: 
1.268     brouard   404:   Revision 1.267  2017/05/13 10:25:05  brouard
                    405:   Summary: temporary save for backprojection
                    406: 
1.267     brouard   407:   Revision 1.266  2017/05/13 07:26:12  brouard
                    408:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    409: 
1.266     brouard   410:   Revision 1.265  2017/04/26 16:22:11  brouard
                    411:   Summary: imach 0.99r13 Some bugs fixed
                    412: 
1.265     brouard   413:   Revision 1.264  2017/04/26 06:01:29  brouard
                    414:   Summary: Labels in graphs
                    415: 
1.264     brouard   416:   Revision 1.263  2017/04/24 15:23:15  brouard
                    417:   Summary: to save
                    418: 
1.263     brouard   419:   Revision 1.262  2017/04/18 16:48:12  brouard
                    420:   *** empty log message ***
                    421: 
1.262     brouard   422:   Revision 1.261  2017/04/05 10:14:09  brouard
                    423:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    424: 
1.261     brouard   425:   Revision 1.260  2017/04/04 17:46:59  brouard
                    426:   Summary: Gnuplot indexations fixed (humm)
                    427: 
1.260     brouard   428:   Revision 1.259  2017/04/04 13:01:16  brouard
                    429:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    430: 
1.259     brouard   431:   Revision 1.258  2017/04/03 10:17:47  brouard
                    432:   Summary: Version 0.99r12
                    433: 
                    434:   Some cleanings, conformed with updated documentation.
                    435: 
1.258     brouard   436:   Revision 1.257  2017/03/29 16:53:30  brouard
                    437:   Summary: Temp
                    438: 
1.257     brouard   439:   Revision 1.256  2017/03/27 05:50:23  brouard
                    440:   Summary: Temporary
                    441: 
1.256     brouard   442:   Revision 1.255  2017/03/08 16:02:28  brouard
                    443:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    444: 
1.255     brouard   445:   Revision 1.254  2017/03/08 07:13:00  brouard
                    446:   Summary: Fixing data parameter line
                    447: 
1.254     brouard   448:   Revision 1.253  2016/12/15 11:59:41  brouard
                    449:   Summary: 0.99 in progress
                    450: 
1.253     brouard   451:   Revision 1.252  2016/09/15 21:15:37  brouard
                    452:   *** empty log message ***
                    453: 
1.252     brouard   454:   Revision 1.251  2016/09/15 15:01:13  brouard
                    455:   Summary: not working
                    456: 
1.251     brouard   457:   Revision 1.250  2016/09/08 16:07:27  brouard
                    458:   Summary: continue
                    459: 
1.250     brouard   460:   Revision 1.249  2016/09/07 17:14:18  brouard
                    461:   Summary: Starting values from frequencies
                    462: 
1.249     brouard   463:   Revision 1.248  2016/09/07 14:10:18  brouard
                    464:   *** empty log message ***
                    465: 
1.248     brouard   466:   Revision 1.247  2016/09/02 11:11:21  brouard
                    467:   *** empty log message ***
                    468: 
1.247     brouard   469:   Revision 1.246  2016/09/02 08:49:22  brouard
                    470:   *** empty log message ***
                    471: 
1.246     brouard   472:   Revision 1.245  2016/09/02 07:25:01  brouard
                    473:   *** empty log message ***
                    474: 
1.245     brouard   475:   Revision 1.244  2016/09/02 07:17:34  brouard
                    476:   *** empty log message ***
                    477: 
1.244     brouard   478:   Revision 1.243  2016/09/02 06:45:35  brouard
                    479:   *** empty log message ***
                    480: 
1.243     brouard   481:   Revision 1.242  2016/08/30 15:01:20  brouard
                    482:   Summary: Fixing a lots
                    483: 
1.242     brouard   484:   Revision 1.241  2016/08/29 17:17:25  brouard
                    485:   Summary: gnuplot problem in Back projection to fix
                    486: 
1.241     brouard   487:   Revision 1.240  2016/08/29 07:53:18  brouard
                    488:   Summary: Better
                    489: 
1.240     brouard   490:   Revision 1.239  2016/08/26 15:51:03  brouard
                    491:   Summary: Improvement in Powell output in order to copy and paste
                    492: 
                    493:   Author:
                    494: 
1.239     brouard   495:   Revision 1.238  2016/08/26 14:23:35  brouard
                    496:   Summary: Starting tests of 0.99
                    497: 
1.238     brouard   498:   Revision 1.237  2016/08/26 09:20:19  brouard
                    499:   Summary: to valgrind
                    500: 
1.237     brouard   501:   Revision 1.236  2016/08/25 10:50:18  brouard
                    502:   *** empty log message ***
                    503: 
1.236     brouard   504:   Revision 1.235  2016/08/25 06:59:23  brouard
                    505:   *** empty log message ***
                    506: 
1.235     brouard   507:   Revision 1.234  2016/08/23 16:51:20  brouard
                    508:   *** empty log message ***
                    509: 
1.234     brouard   510:   Revision 1.233  2016/08/23 07:40:50  brouard
                    511:   Summary: not working
                    512: 
1.233     brouard   513:   Revision 1.232  2016/08/22 14:20:21  brouard
                    514:   Summary: not working
                    515: 
1.232     brouard   516:   Revision 1.231  2016/08/22 07:17:15  brouard
                    517:   Summary: not working
                    518: 
1.231     brouard   519:   Revision 1.230  2016/08/22 06:55:53  brouard
                    520:   Summary: Not working
                    521: 
1.230     brouard   522:   Revision 1.229  2016/07/23 09:45:53  brouard
                    523:   Summary: Completing for func too
                    524: 
1.229     brouard   525:   Revision 1.228  2016/07/22 17:45:30  brouard
                    526:   Summary: Fixing some arrays, still debugging
                    527: 
1.227     brouard   528:   Revision 1.226  2016/07/12 18:42:34  brouard
                    529:   Summary: temp
                    530: 
1.226     brouard   531:   Revision 1.225  2016/07/12 08:40:03  brouard
                    532:   Summary: saving but not running
                    533: 
1.225     brouard   534:   Revision 1.224  2016/07/01 13:16:01  brouard
                    535:   Summary: Fixes
                    536: 
1.224     brouard   537:   Revision 1.223  2016/02/19 09:23:35  brouard
                    538:   Summary: temporary
                    539: 
1.223     brouard   540:   Revision 1.222  2016/02/17 08:14:50  brouard
                    541:   Summary: Probably last 0.98 stable version 0.98r6
                    542: 
1.222     brouard   543:   Revision 1.221  2016/02/15 23:35:36  brouard
                    544:   Summary: minor bug
                    545: 
1.220     brouard   546:   Revision 1.219  2016/02/15 00:48:12  brouard
                    547:   *** empty log message ***
                    548: 
1.219     brouard   549:   Revision 1.218  2016/02/12 11:29:23  brouard
                    550:   Summary: 0.99 Back projections
                    551: 
1.218     brouard   552:   Revision 1.217  2015/12/23 17:18:31  brouard
                    553:   Summary: Experimental backcast
                    554: 
1.217     brouard   555:   Revision 1.216  2015/12/18 17:32:11  brouard
                    556:   Summary: 0.98r4 Warning and status=-2
                    557: 
                    558:   Version 0.98r4 is now:
                    559:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    560:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    561:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    562: 
1.216     brouard   563:   Revision 1.215  2015/12/16 08:52:24  brouard
                    564:   Summary: 0.98r4 working
                    565: 
1.215     brouard   566:   Revision 1.214  2015/12/16 06:57:54  brouard
                    567:   Summary: temporary not working
                    568: 
1.214     brouard   569:   Revision 1.213  2015/12/11 18:22:17  brouard
                    570:   Summary: 0.98r4
                    571: 
1.213     brouard   572:   Revision 1.212  2015/11/21 12:47:24  brouard
                    573:   Summary: minor typo
                    574: 
1.212     brouard   575:   Revision 1.211  2015/11/21 12:41:11  brouard
                    576:   Summary: 0.98r3 with some graph of projected cross-sectional
                    577: 
                    578:   Author: Nicolas Brouard
                    579: 
1.211     brouard   580:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   581:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   582:   Summary: Adding ftolpl parameter
                    583:   Author: N Brouard
                    584: 
                    585:   We had difficulties to get smoothed confidence intervals. It was due
                    586:   to the period prevalence which wasn't computed accurately. The inner
                    587:   parameter ftolpl is now an outer parameter of the .imach parameter
                    588:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    589:   computation are long.
                    590: 
1.209     brouard   591:   Revision 1.208  2015/11/17 14:31:57  brouard
                    592:   Summary: temporary
                    593: 
1.208     brouard   594:   Revision 1.207  2015/10/27 17:36:57  brouard
                    595:   *** empty log message ***
                    596: 
1.207     brouard   597:   Revision 1.206  2015/10/24 07:14:11  brouard
                    598:   *** empty log message ***
                    599: 
1.206     brouard   600:   Revision 1.205  2015/10/23 15:50:53  brouard
                    601:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    602: 
1.205     brouard   603:   Revision 1.204  2015/10/01 16:20:26  brouard
                    604:   Summary: Some new graphs of contribution to likelihood
                    605: 
1.204     brouard   606:   Revision 1.203  2015/09/30 17:45:14  brouard
                    607:   Summary: looking at better estimation of the hessian
                    608: 
                    609:   Also a better criteria for convergence to the period prevalence And
                    610:   therefore adding the number of years needed to converge. (The
                    611:   prevalence in any alive state shold sum to one
                    612: 
1.203     brouard   613:   Revision 1.202  2015/09/22 19:45:16  brouard
                    614:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    615: 
1.202     brouard   616:   Revision 1.201  2015/09/15 17:34:58  brouard
                    617:   Summary: 0.98r0
                    618: 
                    619:   - Some new graphs like suvival functions
                    620:   - Some bugs fixed like model=1+age+V2.
                    621: 
1.201     brouard   622:   Revision 1.200  2015/09/09 16:53:55  brouard
                    623:   Summary: Big bug thanks to Flavia
                    624: 
                    625:   Even model=1+age+V2. did not work anymore
                    626: 
1.200     brouard   627:   Revision 1.199  2015/09/07 14:09:23  brouard
                    628:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    629: 
1.199     brouard   630:   Revision 1.198  2015/09/03 07:14:39  brouard
                    631:   Summary: 0.98q5 Flavia
                    632: 
1.198     brouard   633:   Revision 1.197  2015/09/01 18:24:39  brouard
                    634:   *** empty log message ***
                    635: 
1.197     brouard   636:   Revision 1.196  2015/08/18 23:17:52  brouard
                    637:   Summary: 0.98q5
                    638: 
1.196     brouard   639:   Revision 1.195  2015/08/18 16:28:39  brouard
                    640:   Summary: Adding a hack for testing purpose
                    641: 
                    642:   After reading the title, ftol and model lines, if the comment line has
                    643:   a q, starting with #q, the answer at the end of the run is quit. It
                    644:   permits to run test files in batch with ctest. The former workaround was
                    645:   $ echo q | imach foo.imach
                    646: 
1.195     brouard   647:   Revision 1.194  2015/08/18 13:32:00  brouard
                    648:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    649: 
1.194     brouard   650:   Revision 1.193  2015/08/04 07:17:42  brouard
                    651:   Summary: 0.98q4
                    652: 
1.193     brouard   653:   Revision 1.192  2015/07/16 16:49:02  brouard
                    654:   Summary: Fixing some outputs
                    655: 
1.192     brouard   656:   Revision 1.191  2015/07/14 10:00:33  brouard
                    657:   Summary: Some fixes
                    658: 
1.191     brouard   659:   Revision 1.190  2015/05/05 08:51:13  brouard
                    660:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    661: 
                    662:   Fix 1+age+.
                    663: 
1.190     brouard   664:   Revision 1.189  2015/04/30 14:45:16  brouard
                    665:   Summary: 0.98q2
                    666: 
1.189     brouard   667:   Revision 1.188  2015/04/30 08:27:53  brouard
                    668:   *** empty log message ***
                    669: 
1.188     brouard   670:   Revision 1.187  2015/04/29 09:11:15  brouard
                    671:   *** empty log message ***
                    672: 
1.187     brouard   673:   Revision 1.186  2015/04/23 12:01:52  brouard
                    674:   Summary: V1*age is working now, version 0.98q1
                    675: 
                    676:   Some codes had been disabled in order to simplify and Vn*age was
                    677:   working in the optimization phase, ie, giving correct MLE parameters,
                    678:   but, as usual, outputs were not correct and program core dumped.
                    679: 
1.186     brouard   680:   Revision 1.185  2015/03/11 13:26:42  brouard
                    681:   Summary: Inclusion of compile and links command line for Intel Compiler
                    682: 
1.185     brouard   683:   Revision 1.184  2015/03/11 11:52:39  brouard
                    684:   Summary: Back from Windows 8. Intel Compiler
                    685: 
1.184     brouard   686:   Revision 1.183  2015/03/10 20:34:32  brouard
                    687:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    688: 
                    689:   We use directest instead of original Powell test; probably no
                    690:   incidence on the results, but better justifications;
                    691:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    692:   wrong results.
                    693: 
1.183     brouard   694:   Revision 1.182  2015/02/12 08:19:57  brouard
                    695:   Summary: Trying to keep directest which seems simpler and more general
                    696:   Author: Nicolas Brouard
                    697: 
1.182     brouard   698:   Revision 1.181  2015/02/11 23:22:24  brouard
                    699:   Summary: Comments on Powell added
                    700: 
                    701:   Author:
                    702: 
1.181     brouard   703:   Revision 1.180  2015/02/11 17:33:45  brouard
                    704:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    705: 
1.180     brouard   706:   Revision 1.179  2015/01/04 09:57:06  brouard
                    707:   Summary: back to OS/X
                    708: 
1.179     brouard   709:   Revision 1.178  2015/01/04 09:35:48  brouard
                    710:   *** empty log message ***
                    711: 
1.178     brouard   712:   Revision 1.177  2015/01/03 18:40:56  brouard
                    713:   Summary: Still testing ilc32 on OSX
                    714: 
1.177     brouard   715:   Revision 1.176  2015/01/03 16:45:04  brouard
                    716:   *** empty log message ***
                    717: 
1.176     brouard   718:   Revision 1.175  2015/01/03 16:33:42  brouard
                    719:   *** empty log message ***
                    720: 
1.175     brouard   721:   Revision 1.174  2015/01/03 16:15:49  brouard
                    722:   Summary: Still in cross-compilation
                    723: 
1.174     brouard   724:   Revision 1.173  2015/01/03 12:06:26  brouard
                    725:   Summary: trying to detect cross-compilation
                    726: 
1.173     brouard   727:   Revision 1.172  2014/12/27 12:07:47  brouard
                    728:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    729: 
1.172     brouard   730:   Revision 1.171  2014/12/23 13:26:59  brouard
                    731:   Summary: Back from Visual C
                    732: 
                    733:   Still problem with utsname.h on Windows
                    734: 
1.171     brouard   735:   Revision 1.170  2014/12/23 11:17:12  brouard
                    736:   Summary: Cleaning some \%% back to %%
                    737: 
                    738:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    739: 
1.170     brouard   740:   Revision 1.169  2014/12/22 23:08:31  brouard
                    741:   Summary: 0.98p
                    742: 
                    743:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    744: 
1.169     brouard   745:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   746:   Summary: update
1.169     brouard   747: 
1.168     brouard   748:   Revision 1.167  2014/12/22 13:50:56  brouard
                    749:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    750: 
                    751:   Testing on Linux 64
                    752: 
1.167     brouard   753:   Revision 1.166  2014/12/22 11:40:47  brouard
                    754:   *** empty log message ***
                    755: 
1.166     brouard   756:   Revision 1.165  2014/12/16 11:20:36  brouard
                    757:   Summary: After compiling on Visual C
                    758: 
                    759:   * imach.c (Module): Merging 1.61 to 1.162
                    760: 
1.165     brouard   761:   Revision 1.164  2014/12/16 10:52:11  brouard
                    762:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    763: 
                    764:   * imach.c (Module): Merging 1.61 to 1.162
                    765: 
1.164     brouard   766:   Revision 1.163  2014/12/16 10:30:11  brouard
                    767:   * imach.c (Module): Merging 1.61 to 1.162
                    768: 
1.163     brouard   769:   Revision 1.162  2014/09/25 11:43:39  brouard
                    770:   Summary: temporary backup 0.99!
                    771: 
1.162     brouard   772:   Revision 1.1  2014/09/16 11:06:58  brouard
                    773:   Summary: With some code (wrong) for nlopt
                    774: 
                    775:   Author:
                    776: 
                    777:   Revision 1.161  2014/09/15 20:41:41  brouard
                    778:   Summary: Problem with macro SQR on Intel compiler
                    779: 
1.161     brouard   780:   Revision 1.160  2014/09/02 09:24:05  brouard
                    781:   *** empty log message ***
                    782: 
1.160     brouard   783:   Revision 1.159  2014/09/01 10:34:10  brouard
                    784:   Summary: WIN32
                    785:   Author: Brouard
                    786: 
1.159     brouard   787:   Revision 1.158  2014/08/27 17:11:51  brouard
                    788:   *** empty log message ***
                    789: 
1.158     brouard   790:   Revision 1.157  2014/08/27 16:26:55  brouard
                    791:   Summary: Preparing windows Visual studio version
                    792:   Author: Brouard
                    793: 
                    794:   In order to compile on Visual studio, time.h is now correct and time_t
                    795:   and tm struct should be used. difftime should be used but sometimes I
                    796:   just make the differences in raw time format (time(&now).
                    797:   Trying to suppress #ifdef LINUX
                    798:   Add xdg-open for __linux in order to open default browser.
                    799: 
1.157     brouard   800:   Revision 1.156  2014/08/25 20:10:10  brouard
                    801:   *** empty log message ***
                    802: 
1.156     brouard   803:   Revision 1.155  2014/08/25 18:32:34  brouard
                    804:   Summary: New compile, minor changes
                    805:   Author: Brouard
                    806: 
1.155     brouard   807:   Revision 1.154  2014/06/20 17:32:08  brouard
                    808:   Summary: Outputs now all graphs of convergence to period prevalence
                    809: 
1.154     brouard   810:   Revision 1.153  2014/06/20 16:45:46  brouard
                    811:   Summary: If 3 live state, convergence to period prevalence on same graph
                    812:   Author: Brouard
                    813: 
1.153     brouard   814:   Revision 1.152  2014/06/18 17:54:09  brouard
                    815:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    816: 
1.152     brouard   817:   Revision 1.151  2014/06/18 16:43:30  brouard
                    818:   *** empty log message ***
                    819: 
1.151     brouard   820:   Revision 1.150  2014/06/18 16:42:35  brouard
                    821:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    822:   Author: brouard
                    823: 
1.150     brouard   824:   Revision 1.149  2014/06/18 15:51:14  brouard
                    825:   Summary: Some fixes in parameter files errors
                    826:   Author: Nicolas Brouard
                    827: 
1.149     brouard   828:   Revision 1.148  2014/06/17 17:38:48  brouard
                    829:   Summary: Nothing new
                    830:   Author: Brouard
                    831: 
                    832:   Just a new packaging for OS/X version 0.98nS
                    833: 
1.148     brouard   834:   Revision 1.147  2014/06/16 10:33:11  brouard
                    835:   *** empty log message ***
                    836: 
1.147     brouard   837:   Revision 1.146  2014/06/16 10:20:28  brouard
                    838:   Summary: Merge
                    839:   Author: Brouard
                    840: 
                    841:   Merge, before building revised version.
                    842: 
1.146     brouard   843:   Revision 1.145  2014/06/10 21:23:15  brouard
                    844:   Summary: Debugging with valgrind
                    845:   Author: Nicolas Brouard
                    846: 
                    847:   Lot of changes in order to output the results with some covariates
                    848:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    849:   improve the code.
                    850:   No more memory valgrind error but a lot has to be done in order to
                    851:   continue the work of splitting the code into subroutines.
                    852:   Also, decodemodel has been improved. Tricode is still not
                    853:   optimal. nbcode should be improved. Documentation has been added in
                    854:   the source code.
                    855: 
1.144     brouard   856:   Revision 1.143  2014/01/26 09:45:38  brouard
                    857:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    858: 
                    859:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    860:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    861: 
1.143     brouard   862:   Revision 1.142  2014/01/26 03:57:36  brouard
                    863:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    864: 
                    865:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    866: 
1.142     brouard   867:   Revision 1.141  2014/01/26 02:42:01  brouard
                    868:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    869: 
1.141     brouard   870:   Revision 1.140  2011/09/02 10:37:54  brouard
                    871:   Summary: times.h is ok with mingw32 now.
                    872: 
1.140     brouard   873:   Revision 1.139  2010/06/14 07:50:17  brouard
                    874:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    875:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    876: 
1.139     brouard   877:   Revision 1.138  2010/04/30 18:19:40  brouard
                    878:   *** empty log message ***
                    879: 
1.138     brouard   880:   Revision 1.137  2010/04/29 18:11:38  brouard
                    881:   (Module): Checking covariates for more complex models
                    882:   than V1+V2. A lot of change to be done. Unstable.
                    883: 
1.137     brouard   884:   Revision 1.136  2010/04/26 20:30:53  brouard
                    885:   (Module): merging some libgsl code. Fixing computation
                    886:   of likelione (using inter/intrapolation if mle = 0) in order to
                    887:   get same likelihood as if mle=1.
                    888:   Some cleaning of code and comments added.
                    889: 
1.136     brouard   890:   Revision 1.135  2009/10/29 15:33:14  brouard
                    891:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    892: 
1.135     brouard   893:   Revision 1.134  2009/10/29 13:18:53  brouard
                    894:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    895: 
1.134     brouard   896:   Revision 1.133  2009/07/06 10:21:25  brouard
                    897:   just nforces
                    898: 
1.133     brouard   899:   Revision 1.132  2009/07/06 08:22:05  brouard
                    900:   Many tings
                    901: 
1.132     brouard   902:   Revision 1.131  2009/06/20 16:22:47  brouard
                    903:   Some dimensions resccaled
                    904: 
1.131     brouard   905:   Revision 1.130  2009/05/26 06:44:34  brouard
                    906:   (Module): Max Covariate is now set to 20 instead of 8. A
                    907:   lot of cleaning with variables initialized to 0. Trying to make
                    908:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    909: 
1.130     brouard   910:   Revision 1.129  2007/08/31 13:49:27  lievre
                    911:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    912: 
1.129     lievre    913:   Revision 1.128  2006/06/30 13:02:05  brouard
                    914:   (Module): Clarifications on computing e.j
                    915: 
1.128     brouard   916:   Revision 1.127  2006/04/28 18:11:50  brouard
                    917:   (Module): Yes the sum of survivors was wrong since
                    918:   imach-114 because nhstepm was no more computed in the age
                    919:   loop. Now we define nhstepma in the age loop.
                    920:   (Module): In order to speed up (in case of numerous covariates) we
                    921:   compute health expectancies (without variances) in a first step
                    922:   and then all the health expectancies with variances or standard
                    923:   deviation (needs data from the Hessian matrices) which slows the
                    924:   computation.
                    925:   In the future we should be able to stop the program is only health
                    926:   expectancies and graph are needed without standard deviations.
                    927: 
1.127     brouard   928:   Revision 1.126  2006/04/28 17:23:28  brouard
                    929:   (Module): Yes the sum of survivors was wrong since
                    930:   imach-114 because nhstepm was no more computed in the age
                    931:   loop. Now we define nhstepma in the age loop.
                    932:   Version 0.98h
                    933: 
1.126     brouard   934:   Revision 1.125  2006/04/04 15:20:31  lievre
                    935:   Errors in calculation of health expectancies. Age was not initialized.
                    936:   Forecasting file added.
                    937: 
                    938:   Revision 1.124  2006/03/22 17:13:53  lievre
                    939:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    940:   The log-likelihood is printed in the log file
                    941: 
                    942:   Revision 1.123  2006/03/20 10:52:43  brouard
                    943:   * imach.c (Module): <title> changed, corresponds to .htm file
                    944:   name. <head> headers where missing.
                    945: 
                    946:   * imach.c (Module): Weights can have a decimal point as for
                    947:   English (a comma might work with a correct LC_NUMERIC environment,
                    948:   otherwise the weight is truncated).
                    949:   Modification of warning when the covariates values are not 0 or
                    950:   1.
                    951:   Version 0.98g
                    952: 
                    953:   Revision 1.122  2006/03/20 09:45:41  brouard
                    954:   (Module): Weights can have a decimal point as for
                    955:   English (a comma might work with a correct LC_NUMERIC environment,
                    956:   otherwise the weight is truncated).
                    957:   Modification of warning when the covariates values are not 0 or
                    958:   1.
                    959:   Version 0.98g
                    960: 
                    961:   Revision 1.121  2006/03/16 17:45:01  lievre
                    962:   * imach.c (Module): Comments concerning covariates added
                    963: 
                    964:   * imach.c (Module): refinements in the computation of lli if
                    965:   status=-2 in order to have more reliable computation if stepm is
                    966:   not 1 month. Version 0.98f
                    967: 
                    968:   Revision 1.120  2006/03/16 15:10:38  lievre
                    969:   (Module): refinements in the computation of lli if
                    970:   status=-2 in order to have more reliable computation if stepm is
                    971:   not 1 month. Version 0.98f
                    972: 
                    973:   Revision 1.119  2006/03/15 17:42:26  brouard
                    974:   (Module): Bug if status = -2, the loglikelihood was
                    975:   computed as likelihood omitting the logarithm. Version O.98e
                    976: 
                    977:   Revision 1.118  2006/03/14 18:20:07  brouard
                    978:   (Module): varevsij Comments added explaining the second
                    979:   table of variances if popbased=1 .
                    980:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    981:   (Module): Function pstamp added
                    982:   (Module): Version 0.98d
                    983: 
                    984:   Revision 1.117  2006/03/14 17:16:22  brouard
                    985:   (Module): varevsij Comments added explaining the second
                    986:   table of variances if popbased=1 .
                    987:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    988:   (Module): Function pstamp added
                    989:   (Module): Version 0.98d
                    990: 
                    991:   Revision 1.116  2006/03/06 10:29:27  brouard
                    992:   (Module): Variance-covariance wrong links and
                    993:   varian-covariance of ej. is needed (Saito).
                    994: 
                    995:   Revision 1.115  2006/02/27 12:17:45  brouard
                    996:   (Module): One freematrix added in mlikeli! 0.98c
                    997: 
                    998:   Revision 1.114  2006/02/26 12:57:58  brouard
                    999:   (Module): Some improvements in processing parameter
                   1000:   filename with strsep.
                   1001: 
                   1002:   Revision 1.113  2006/02/24 14:20:24  brouard
                   1003:   (Module): Memory leaks checks with valgrind and:
                   1004:   datafile was not closed, some imatrix were not freed and on matrix
                   1005:   allocation too.
                   1006: 
                   1007:   Revision 1.112  2006/01/30 09:55:26  brouard
                   1008:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                   1009: 
                   1010:   Revision 1.111  2006/01/25 20:38:18  brouard
                   1011:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1012:   (Module): Comments can be added in data file. Missing date values
                   1013:   can be a simple dot '.'.
                   1014: 
                   1015:   Revision 1.110  2006/01/25 00:51:50  brouard
                   1016:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1017: 
                   1018:   Revision 1.109  2006/01/24 19:37:15  brouard
                   1019:   (Module): Comments (lines starting with a #) are allowed in data.
                   1020: 
                   1021:   Revision 1.108  2006/01/19 18:05:42  lievre
                   1022:   Gnuplot problem appeared...
                   1023:   To be fixed
                   1024: 
                   1025:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1026:   Test existence of gnuplot in imach path
                   1027: 
                   1028:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1029:   Some cleaning and links added in html output
                   1030: 
                   1031:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1032:   *** empty log message ***
                   1033: 
                   1034:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1035:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1036:   (Module): If the status is missing at the last wave but we know
                   1037:   that the person is alive, then we can code his/her status as -2
                   1038:   (instead of missing=-1 in earlier versions) and his/her
                   1039:   contributions to the likelihood is 1 - Prob of dying from last
                   1040:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1041:   the healthy state at last known wave). Version is 0.98
                   1042: 
                   1043:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1044:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1045: 
                   1046:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1047:   Add the possibility to read data file including tab characters.
                   1048: 
                   1049:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1050:   Fix on curr_time
                   1051: 
                   1052:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1053:   Add version for Mac OS X. Just define UNIX in Makefile
                   1054: 
                   1055:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1056:   *** empty log message ***
                   1057: 
                   1058:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1059:   New version 0.97 . First attempt to estimate force of mortality
                   1060:   directly from the data i.e. without the need of knowing the health
                   1061:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1062:   This is the basic analysis of mortality and should be done before any
                   1063:   other analysis, in order to test if the mortality estimated from the
                   1064:   cross-longitudinal survey is different from the mortality estimated
                   1065:   from other sources like vital statistic data.
                   1066: 
                   1067:   The same imach parameter file can be used but the option for mle should be -3.
                   1068: 
1.324     brouard  1069:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1070:   former routines in order to include the new code within the former code.
                   1071: 
                   1072:   The output is very simple: only an estimate of the intercept and of
                   1073:   the slope with 95% confident intervals.
                   1074: 
                   1075:   Current limitations:
                   1076:   A) Even if you enter covariates, i.e. with the
                   1077:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1078:   B) There is no computation of Life Expectancy nor Life Table.
                   1079: 
                   1080:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1081:   Version 0.96d. Population forecasting command line is (temporarily)
                   1082:   suppressed.
                   1083: 
                   1084:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1085:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1086:   rewritten within the same printf. Workaround: many printfs.
                   1087: 
                   1088:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1089:   * imach.c (Repository):
                   1090:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1091:   matrix (cov(a12,c31) instead of numbers.
                   1092: 
                   1093:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1094:   Just cleaning
                   1095: 
                   1096:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1097:   (Module): On windows (cygwin) function asctime_r doesn't
                   1098:   exist so I changed back to asctime which exists.
                   1099:   (Module): Version 0.96b
                   1100: 
                   1101:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1102:   (Module): On windows (cygwin) function asctime_r doesn't
                   1103:   exist so I changed back to asctime which exists.
                   1104: 
                   1105:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1106:   * imach.c (Repository): Duplicated warning errors corrected.
                   1107:   (Repository): Elapsed time after each iteration is now output. It
                   1108:   helps to forecast when convergence will be reached. Elapsed time
                   1109:   is stamped in powell.  We created a new html file for the graphs
                   1110:   concerning matrix of covariance. It has extension -cov.htm.
                   1111: 
                   1112:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1113:   (Module): Some bugs corrected for windows. Also, when
                   1114:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1115:   of the covariance matrix to be input.
                   1116: 
                   1117:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1118:   (Module): Some bugs corrected for windows. Also, when
                   1119:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1120:   of the covariance matrix to be input.
                   1121: 
                   1122:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1123:   * 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.
                   1124: 
                   1125:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1126:   Version 0.96
                   1127: 
                   1128:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1129:   (Module): Change position of html and gnuplot routines and added
                   1130:   routine fileappend.
                   1131: 
                   1132:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1133:   * imach.c (Repository): Check when date of death was earlier that
                   1134:   current date of interview. It may happen when the death was just
                   1135:   prior to the death. In this case, dh was negative and likelihood
                   1136:   was wrong (infinity). We still send an "Error" but patch by
                   1137:   assuming that the date of death was just one stepm after the
                   1138:   interview.
                   1139:   (Repository): Because some people have very long ID (first column)
                   1140:   we changed int to long in num[] and we added a new lvector for
                   1141:   memory allocation. But we also truncated to 8 characters (left
                   1142:   truncation)
                   1143:   (Repository): No more line truncation errors.
                   1144: 
                   1145:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1146:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1147:   place. It differs from routine "prevalence" which may be called
                   1148:   many times. Probs is memory consuming and must be used with
                   1149:   parcimony.
                   1150:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1151: 
                   1152:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1153:   *** empty log message ***
                   1154: 
                   1155:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1156:   Add log in  imach.c and  fullversion number is now printed.
                   1157: 
                   1158: */
                   1159: /*
                   1160:    Interpolated Markov Chain
                   1161: 
                   1162:   Short summary of the programme:
                   1163:   
1.227     brouard  1164:   This program computes Healthy Life Expectancies or State-specific
                   1165:   (if states aren't health statuses) Expectancies from
                   1166:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1167: 
                   1168:   -1- a first survey ("cross") where individuals from different ages
                   1169:   are interviewed on their health status or degree of disability (in
                   1170:   the case of a health survey which is our main interest)
                   1171: 
                   1172:   -2- at least a second wave of interviews ("longitudinal") which
                   1173:   measure each change (if any) in individual health status.  Health
                   1174:   expectancies are computed from the time spent in each health state
                   1175:   according to a model. More health states you consider, more time is
                   1176:   necessary to reach the Maximum Likelihood of the parameters involved
                   1177:   in the model.  The simplest model is the multinomial logistic model
                   1178:   where pij is the probability to be observed in state j at the second
                   1179:   wave conditional to be observed in state i at the first
                   1180:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1181:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1182:   have a more complex model than "constant and age", you should modify
                   1183:   the program where the markup *Covariates have to be included here
                   1184:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1185:   convergence.
                   1186: 
                   1187:   The advantage of this computer programme, compared to a simple
                   1188:   multinomial logistic model, is clear when the delay between waves is not
                   1189:   identical for each individual. Also, if a individual missed an
                   1190:   intermediate interview, the information is lost, but taken into
                   1191:   account using an interpolation or extrapolation.  
                   1192: 
                   1193:   hPijx is the probability to be observed in state i at age x+h
                   1194:   conditional to the observed state i at age x. The delay 'h' can be
                   1195:   split into an exact number (nh*stepm) of unobserved intermediate
                   1196:   states. This elementary transition (by month, quarter,
                   1197:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1198:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1199:   and the contribution of each individual to the likelihood is simply
                   1200:   hPijx.
                   1201: 
                   1202:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1203:   of the life expectancies. It also computes the period (stable) prevalence.
                   1204: 
                   1205: Back prevalence and projections:
1.227     brouard  1206: 
                   1207:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1208:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1209:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1210:    mobilavproj)
                   1211: 
                   1212:     Computes the back prevalence limit for any combination of
                   1213:     covariate values k at any age between ageminpar and agemaxpar and
                   1214:     returns it in **bprlim. In the loops,
                   1215: 
                   1216:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1217:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1218: 
                   1219:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1220:    Computes for any combination of covariates k and any age between bage and fage 
                   1221:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1222:                        oldm=oldms;savm=savms;
1.227     brouard  1223: 
1.267     brouard  1224:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1225:      Computes the transition matrix starting at age 'age' over
                   1226:      'nhstepm*hstepm*stepm' months (i.e. until
                   1227:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1228:      nhstepm*hstepm matrices. 
                   1229: 
                   1230:      Returns p3mat[i][j][h] after calling
                   1231:      p3mat[i][j][h]=matprod2(newm,
                   1232:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1233:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1234:      oldm);
1.226     brouard  1235: 
                   1236: Important routines
                   1237: 
                   1238: - func (or funcone), computes logit (pij) distinguishing
                   1239:   o fixed variables (single or product dummies or quantitative);
                   1240:   o varying variables by:
                   1241:    (1) wave (single, product dummies, quantitative), 
                   1242:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1243:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1244:        % varying dummy (not done) or quantitative (not done);
                   1245: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1246:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1247: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1248:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1249:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1250: 
1.226     brouard  1251: 
                   1252:   
1.324     brouard  1253:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1254:            Institut national d'études démographiques, Paris.
1.126     brouard  1255:   This software have been partly granted by Euro-REVES, a concerted action
                   1256:   from the European Union.
                   1257:   It is copyrighted identically to a GNU software product, ie programme and
                   1258:   software can be distributed freely for non commercial use. Latest version
                   1259:   can be accessed at http://euroreves.ined.fr/imach .
                   1260: 
                   1261:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1262:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1263:   
                   1264:   **********************************************************************/
                   1265: /*
                   1266:   main
                   1267:   read parameterfile
                   1268:   read datafile
                   1269:   concatwav
                   1270:   freqsummary
                   1271:   if (mle >= 1)
                   1272:     mlikeli
                   1273:   print results files
                   1274:   if mle==1 
                   1275:      computes hessian
                   1276:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1277:       begin-prev-date,...
                   1278:   open gnuplot file
                   1279:   open html file
1.145     brouard  1280:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1281:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1282:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1283:     freexexit2 possible for memory heap.
                   1284: 
                   1285:   h Pij x                         | pij_nom  ficrestpij
                   1286:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1287:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1288:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1289: 
                   1290:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1291:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1292:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1293:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1294:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1295: 
1.126     brouard  1296:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1297:   health expectancies
                   1298:   Variance-covariance of DFLE
                   1299:   prevalence()
                   1300:    movingaverage()
                   1301:   varevsij() 
                   1302:   if popbased==1 varevsij(,popbased)
                   1303:   total life expectancies
                   1304:   Variance of period (stable) prevalence
                   1305:  end
                   1306: */
                   1307: 
1.187     brouard  1308: /* #define DEBUG */
                   1309: /* #define DEBUGBRENT */
1.203     brouard  1310: /* #define DEBUGLINMIN */
                   1311: /* #define DEBUGHESS */
                   1312: #define DEBUGHESSIJ
1.224     brouard  1313: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1314: #define POWELL /* Instead of NLOPT */
1.224     brouard  1315: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1316: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1317: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1318: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.359     brouard  1319: /* #define POWELLORIGINCONJUGATE  /\* Don't use conjugate but biggest decrease if valuable *\/ */
                   1320: /* #define NOTMINFIT */
1.126     brouard  1321: 
                   1322: #include <math.h>
                   1323: #include <stdio.h>
                   1324: #include <stdlib.h>
                   1325: #include <string.h>
1.226     brouard  1326: #include <ctype.h>
1.159     brouard  1327: 
                   1328: #ifdef _WIN32
                   1329: #include <io.h>
1.172     brouard  1330: #include <windows.h>
                   1331: #include <tchar.h>
1.159     brouard  1332: #else
1.126     brouard  1333: #include <unistd.h>
1.159     brouard  1334: #endif
1.126     brouard  1335: 
                   1336: #include <limits.h>
                   1337: #include <sys/types.h>
1.171     brouard  1338: 
                   1339: #if defined(__GNUC__)
                   1340: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1341: #endif
                   1342: 
1.126     brouard  1343: #include <sys/stat.h>
                   1344: #include <errno.h>
1.159     brouard  1345: /* extern int errno; */
1.126     brouard  1346: 
1.157     brouard  1347: /* #ifdef LINUX */
                   1348: /* #include <time.h> */
                   1349: /* #include "timeval.h" */
                   1350: /* #else */
                   1351: /* #include <sys/time.h> */
                   1352: /* #endif */
                   1353: 
1.126     brouard  1354: #include <time.h>
                   1355: 
1.136     brouard  1356: #ifdef GSL
                   1357: #include <gsl/gsl_errno.h>
                   1358: #include <gsl/gsl_multimin.h>
                   1359: #endif
                   1360: 
1.167     brouard  1361: 
1.162     brouard  1362: #ifdef NLOPT
                   1363: #include <nlopt.h>
                   1364: typedef struct {
                   1365:   double (* function)(double [] );
                   1366: } myfunc_data ;
                   1367: #endif
                   1368: 
1.126     brouard  1369: /* #include <libintl.h> */
                   1370: /* #define _(String) gettext (String) */
                   1371: 
1.349     brouard  1372: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1373: 
                   1374: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1375: #define GNUPLOTVERSION 5.1
                   1376: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1377: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1378: #define FILENAMELENGTH 256
1.126     brouard  1379: 
                   1380: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1381: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1382: 
1.349     brouard  1383: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1384: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1385: 
                   1386: #define NINTERVMAX 8
1.144     brouard  1387: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1388: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1389: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1390: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1391: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1392: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1393: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1394: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1395: /* #define AGESUP 130 */
1.288     brouard  1396: /* #define AGESUP 150 */
                   1397: #define AGESUP 200
1.268     brouard  1398: #define AGEINF 0
1.218     brouard  1399: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1400: #define AGEBASE 40
1.194     brouard  1401: #define AGEOVERFLOW 1.e20
1.164     brouard  1402: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1403: #ifdef _WIN32
                   1404: #define DIRSEPARATOR '\\'
                   1405: #define CHARSEPARATOR "\\"
                   1406: #define ODIRSEPARATOR '/'
                   1407: #else
1.126     brouard  1408: #define DIRSEPARATOR '/'
                   1409: #define CHARSEPARATOR "/"
                   1410: #define ODIRSEPARATOR '\\'
                   1411: #endif
                   1412: 
1.363   ! brouard  1413: /* $Id: imach.c,v 1.362 2024/06/28 08:00:31 brouard Exp $ */
1.126     brouard  1414: /* $State: Exp $ */
1.196     brouard  1415: #include "version.h"
                   1416: char version[]=__IMACH_VERSION__;
1.360     brouard  1417: char copyright[]="April 2024,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2024";
1.363   ! brouard  1418: char fullversion[]="$Revision: 1.362 $ $Date: 2024/06/28 08:00:31 $"; 
1.126     brouard  1419: char strstart[80];
                   1420: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1421: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1422: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1423: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1424: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1425: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1426: 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  1427: 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  1428: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1429: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1430: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1431: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1432: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1433: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1434: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1435: 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  1436: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1437: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1438: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1439: int ncovvta=0; /*  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
                   1440: int ncovta=0; /*age*V3*V2 +age*V2+agev3+ageV4  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
                   1441: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1442: int ncovva=0; /* +age*V6 + age*V7+ge*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
1.234     brouard  1443: int nsd=0; /**< Total number of single dummy variables (output) */
                   1444: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1445: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1446: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1447: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1448: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1449: int cptcov=0; /* Working variable */
1.334     brouard  1450: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1451: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1452: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1453: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1454: int nlstate=2; /* Number of live states */
                   1455: int ndeath=1; /* Number of dead states */
1.130     brouard  1456: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1457: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1458: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1459: int popbased=0;
                   1460: 
                   1461: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1462: int maxwav=0; /* Maxim number of waves */
                   1463: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1464: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
1.359     brouard  1465: int gipmx = 0;
                   1466: double gsw = 0; /* Global variables on the number of contributions
1.126     brouard  1467:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1468: int mle=1, weightopt=0;
1.126     brouard  1469: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1470: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1471: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1472:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1473: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1474: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1475: 
1.130     brouard  1476: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1477: double **matprod2(); /* test */
1.126     brouard  1478: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1479: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1480: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1481: 
1.136     brouard  1482: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1483: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1484: FILE *ficlog, *ficrespow;
1.130     brouard  1485: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1486: double fretone; /* Only one call to likelihood */
1.130     brouard  1487: long ipmx=0; /* Number of contributions */
1.126     brouard  1488: double sw; /* Sum of weights */
                   1489: char filerespow[FILENAMELENGTH];
                   1490: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1491: FILE *ficresilk;
                   1492: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1493: FILE *ficresprobmorprev;
                   1494: FILE *fichtm, *fichtmcov; /* Html File */
                   1495: FILE *ficreseij;
                   1496: char filerese[FILENAMELENGTH];
                   1497: FILE *ficresstdeij;
                   1498: char fileresstde[FILENAMELENGTH];
                   1499: FILE *ficrescveij;
                   1500: char filerescve[FILENAMELENGTH];
                   1501: FILE  *ficresvij;
                   1502: char fileresv[FILENAMELENGTH];
1.269     brouard  1503: 
1.126     brouard  1504: char title[MAXLINE];
1.234     brouard  1505: char model[MAXLINE]; /**< The model line */
1.217     brouard  1506: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1507: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1508: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1509: char command[FILENAMELENGTH];
                   1510: int  outcmd=0;
                   1511: 
1.217     brouard  1512: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1513: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1514: char filelog[FILENAMELENGTH]; /* Log file */
                   1515: char filerest[FILENAMELENGTH];
                   1516: char fileregp[FILENAMELENGTH];
                   1517: char popfile[FILENAMELENGTH];
                   1518: 
                   1519: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1520: 
1.157     brouard  1521: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1522: /* struct timezone tzp; */
                   1523: /* extern int gettimeofday(); */
                   1524: struct tm tml, *gmtime(), *localtime();
                   1525: 
                   1526: extern time_t time();
                   1527: 
                   1528: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1529: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1530: time_t   rlast_btime; /* raw time */
1.157     brouard  1531: struct tm tm;
                   1532: 
1.126     brouard  1533: char strcurr[80], strfor[80];
                   1534: 
                   1535: char *endptr;
                   1536: long lval;
                   1537: double dval;
                   1538: 
1.362     brouard  1539: /* This for praxis gegen */
                   1540:   /* int prin=1; */
                   1541:   double h0=0.25;
                   1542:   double macheps;
                   1543:   double ffmin;
                   1544: 
1.126     brouard  1545: #define NR_END 1
                   1546: #define FREE_ARG char*
                   1547: #define FTOL 1.0e-10
                   1548: 
                   1549: #define NRANSI 
1.240     brouard  1550: #define ITMAX 200
                   1551: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1552: 
                   1553: #define TOL 2.0e-4 
                   1554: 
                   1555: #define CGOLD 0.3819660 
                   1556: #define ZEPS 1.0e-10 
                   1557: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1558: 
                   1559: #define GOLD 1.618034 
                   1560: #define GLIMIT 100.0 
                   1561: #define TINY 1.0e-20 
                   1562: 
                   1563: static double maxarg1,maxarg2;
                   1564: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1565: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1566:   
                   1567: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1568: #define rint(a) floor(a+0.5)
1.166     brouard  1569: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1570: #define mytinydouble 1.0e-16
1.166     brouard  1571: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1572: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1573: /* static double dsqrarg; */
                   1574: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1575: static double sqrarg;
                   1576: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1577: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1578: int agegomp= AGEGOMP;
                   1579: 
                   1580: int imx; 
                   1581: int stepm=1;
                   1582: /* Stepm, step in month: minimum step interpolation*/
                   1583: 
                   1584: int estepm;
                   1585: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1586: 
                   1587: int m,nb;
                   1588: long *num;
1.197     brouard  1589: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1590: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1591:                   covariate for which somebody answered excluding 
                   1592:                   undefined. Usually 2: 0 and 1. */
                   1593: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1594:                             covariate for which somebody answered including 
                   1595:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1596: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1597: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1598: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1599: 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  1600: double *ageexmed,*agecens;
                   1601: double dateintmean=0;
1.296     brouard  1602:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1603:   double anprojf, mprojf, jprojf;
1.126     brouard  1604: 
1.296     brouard  1605:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1606:   double anbackf, mbackf, jbackf;
                   1607:   double jintmean,mintmean,aintmean;  
1.126     brouard  1608: double *weight;
                   1609: int **s; /* Status */
1.141     brouard  1610: double *agedc;
1.145     brouard  1611: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1612:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1613:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1614: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1615: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1616: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1617: double  idx; 
                   1618: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1619: /* Some documentation */
                   1620:       /*   Design original data
                   1621:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1622:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1623:        *                                                             ntv=3     nqtv=1
1.330     brouard  1624:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1625:        * For time varying covariate, quanti or dummies
                   1626:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1627:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1628:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1629:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1630:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1631:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1632:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1633:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1634:        */
                   1635: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1636: /* 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
                   1637:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1638:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1639: */
1.349     brouard  1640: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1641: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1642: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1643:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1644:                                                                /* product without age, 3 for age and double product   */
                   1645: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1646:                                                                 /*(single or product without age), 2 dummy*/
                   1647:                                                                /* with age product, 3 quant with age product*/
                   1648: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1649: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1650: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1651: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1652: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1653: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1654: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1655: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1656: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1657: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1658: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1659: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1660: /* model="V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   1661: /*  p Tvard[1][1]@21 = {6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}*/
1.354     brouard  1662: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1663: /* p Tvardk[1][1]@24 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0}*/
                   1664: /* p Tvardk[1][1]@22 = {0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0} */
1.349     brouard  1665: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1666: /* 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  1667: /* 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  1668: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1669: /* Type                    */
                   1670: /* V         1  2  3  4  5 */
                   1671: /*           F  F  V  V  V */
                   1672: /*           D  Q  D  D  Q */
                   1673: /*                         */
                   1674: int *TvarsD;
1.330     brouard  1675: int *TnsdVar;
1.234     brouard  1676: int *TvarsDind;
                   1677: int *TvarsQ;
                   1678: int *TvarsQind;
                   1679: 
1.318     brouard  1680: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1681: int nresult=0;
1.258     brouard  1682: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1683: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1684: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1685: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1686: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1687: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1688: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1689: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1690: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1691: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1692: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1693: 
                   1694: /* 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
                   1695:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1696:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1697: */
1.234     brouard  1698: /* 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  1699: 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 */
                   1700: 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 */
                   1701: 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 */
                   1702: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1703: 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 */
                   1704: 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  1705: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1706: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1707: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1708: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1709: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1710: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1711: 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 */
                   1712: 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  1713: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1714: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1715: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1716: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1717: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1718: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1719:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1720:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1721:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1722:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1723:       /* TvarVVind={2,5,5,6,6}, for V3 and then the product V1*V3 is decomposed into V1 and V3 and V1*V3*age into 6,6 */              
1.230     brouard  1724: int *Tvarsel; /**< Selected covariates for output */
                   1725: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1726: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
1.227     brouard  1727: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1728: 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  1729: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1730: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1731: int *Tage;
1.227     brouard  1732: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1733: 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  1734: 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*/ 
                   1735: 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  1736: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1737: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1738: int **Tvard;
1.330     brouard  1739: int **Tvardk;
1.227     brouard  1740: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1741: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1742: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1743:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1744:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1745: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1746: double *lsurv, *lpop, *tpop;
                   1747: 
1.231     brouard  1748: #define FD 1; /* Fixed dummy covariate */
                   1749: #define FQ 2; /* Fixed quantitative covariate */
                   1750: #define FP 3; /* Fixed product covariate */
                   1751: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1752: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1753: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1754: #define VD 10; /* Varying dummy covariate */
                   1755: #define VQ 11; /* Varying quantitative covariate */
                   1756: #define VP 12; /* Varying product covariate */
                   1757: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1758: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1759: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1760: #define APFD 16; /* Age product * fixed dummy covariate */
                   1761: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1762: #define APVD 18; /* Age product * varying dummy covariate */
                   1763: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1764: 
                   1765: #define FTYPE 1; /* Fixed covariate */
                   1766: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1767: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1768: 
                   1769: struct kmodel{
                   1770:        int maintype; /* main type */
                   1771:        int subtype; /* subtype */
                   1772: };
                   1773: struct kmodel modell[NCOVMAX];
                   1774: 
1.143     brouard  1775: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1776: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1777: 
                   1778: /**************** split *************************/
                   1779: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1780: {
                   1781:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1782:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1783:   */ 
                   1784:   char *ss;                            /* pointer */
1.186     brouard  1785:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1786: 
                   1787:   l1 = strlen(path );                  /* length of path */
                   1788:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1789:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1790:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1791:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1792:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1793:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1794:     /* get current working directory */
                   1795:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1796: #ifdef WIN32
                   1797:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1798: #else
                   1799:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1800: #endif
1.126     brouard  1801:       return( GLOCK_ERROR_GETCWD );
                   1802:     }
                   1803:     /* got dirc from getcwd*/
                   1804:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1805:   } else {                             /* strip directory from path */
1.126     brouard  1806:     ss++;                              /* after this, the filename */
                   1807:     l2 = strlen( ss );                 /* length of filename */
                   1808:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1809:     strcpy( name, ss );                /* save file name */
                   1810:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1811:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1812:     printf(" DIRC2 = %s \n",dirc);
                   1813:   }
                   1814:   /* We add a separator at the end of dirc if not exists */
                   1815:   l1 = strlen( dirc );                 /* length of directory */
                   1816:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1817:     dirc[l1] =  DIRSEPARATOR;
                   1818:     dirc[l1+1] = 0; 
                   1819:     printf(" DIRC3 = %s \n",dirc);
                   1820:   }
                   1821:   ss = strrchr( name, '.' );           /* find last / */
                   1822:   if (ss >0){
                   1823:     ss++;
                   1824:     strcpy(ext,ss);                    /* save extension */
                   1825:     l1= strlen( name);
                   1826:     l2= strlen(ss)+1;
                   1827:     strncpy( finame, name, l1-l2);
                   1828:     finame[l1-l2]= 0;
                   1829:   }
                   1830: 
                   1831:   return( 0 );                         /* we're done */
                   1832: }
                   1833: 
                   1834: 
                   1835: /******************************************/
                   1836: 
                   1837: void replace_back_to_slash(char *s, char*t)
                   1838: {
                   1839:   int i;
                   1840:   int lg=0;
                   1841:   i=0;
                   1842:   lg=strlen(t);
                   1843:   for(i=0; i<= lg; i++) {
                   1844:     (s[i] = t[i]);
                   1845:     if (t[i]== '\\') s[i]='/';
                   1846:   }
                   1847: }
                   1848: 
1.132     brouard  1849: char *trimbb(char *out, char *in)
1.137     brouard  1850: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1851:   char *s;
                   1852:   s=out;
                   1853:   while (*in != '\0'){
1.137     brouard  1854:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1855:       in++;
                   1856:     }
                   1857:     *out++ = *in++;
                   1858:   }
                   1859:   *out='\0';
                   1860:   return s;
                   1861: }
                   1862: 
1.351     brouard  1863: char *trimbtab(char *out, char *in)
                   1864: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1865:   char *s;
                   1866:   s=out;
                   1867:   while (*in != '\0'){
                   1868:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1869:       in++;
                   1870:     }
                   1871:     *out++ = *in++;
                   1872:   }
                   1873:   *out='\0';
                   1874:   return s;
                   1875: }
                   1876: 
1.187     brouard  1877: /* char *substrchaine(char *out, char *in, char *chain) */
                   1878: /* { */
                   1879: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1880: /*   char *s, *t; */
                   1881: /*   t=in;s=out; */
                   1882: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1883: /*     *out++ = *in++; */
                   1884: /*   } */
                   1885: 
                   1886: /*   /\* *in matches *chain *\/ */
                   1887: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1888: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1889: /*   } */
                   1890: /*   in--; chain--; */
                   1891: /*   while ( (*in != '\0')){ */
                   1892: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1893: /*     *out++ = *in++; */
                   1894: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1895: /*   } */
                   1896: /*   *out='\0'; */
                   1897: /*   out=s; */
                   1898: /*   return out; */
                   1899: /* } */
                   1900: char *substrchaine(char *out, char *in, char *chain)
                   1901: {
                   1902:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1903:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1904: 
                   1905:   char *strloc;
                   1906: 
1.349     brouard  1907:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1908:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1909:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out); /* strloc=+age*age+V2 chain="+age*age", out="V1+V1*age+age*age+V2" */
1.187     brouard  1910:   if(strloc != NULL){ 
1.349     brouard  1911:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1912:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1); /* move number of bytes corresponding to the length of "+V2" which is 3, plus one is 4 (including the null)*/
                   1913:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1914:   }
1.349     brouard  1915:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);  /* strloc=+V2 chain="+age*age", in="V1+V1*age+age*age+V2", out="V1+V1*age+V2" */
1.187     brouard  1916:   return out;
                   1917: }
                   1918: 
                   1919: 
1.145     brouard  1920: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1921: {
1.187     brouard  1922:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1923:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1924:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1925:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1926:   */
1.160     brouard  1927:   char *s, *t;
1.145     brouard  1928:   t=in;s=in;
                   1929:   while ((*in != occ) && (*in != '\0')){
                   1930:     *alocc++ = *in++;
                   1931:   }
                   1932:   if( *in == occ){
                   1933:     *(alocc)='\0';
                   1934:     s=++in;
                   1935:   }
                   1936:  
                   1937:   if (s == t) {/* occ not found */
                   1938:     *(alocc-(in-s))='\0';
                   1939:     in=s;
                   1940:   }
                   1941:   while ( *in != '\0'){
                   1942:     *blocc++ = *in++;
                   1943:   }
                   1944: 
                   1945:   *blocc='\0';
                   1946:   return t;
                   1947: }
1.137     brouard  1948: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1949: {
1.187     brouard  1950:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1951:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1952:      gives blocc="abcdef2ghi" and alocc="j".
                   1953:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1954:   */
                   1955:   char *s, *t;
                   1956:   t=in;s=in;
                   1957:   while (*in != '\0'){
                   1958:     while( *in == occ){
                   1959:       *blocc++ = *in++;
                   1960:       s=in;
                   1961:     }
                   1962:     *blocc++ = *in++;
                   1963:   }
                   1964:   if (s == t) /* occ not found */
                   1965:     *(blocc-(in-s))='\0';
                   1966:   else
                   1967:     *(blocc-(in-s)-1)='\0';
                   1968:   in=s;
                   1969:   while ( *in != '\0'){
                   1970:     *alocc++ = *in++;
                   1971:   }
                   1972: 
                   1973:   *alocc='\0';
                   1974:   return s;
                   1975: }
                   1976: 
1.126     brouard  1977: int nbocc(char *s, char occ)
                   1978: {
                   1979:   int i,j=0;
                   1980:   int lg=20;
                   1981:   i=0;
                   1982:   lg=strlen(s);
                   1983:   for(i=0; i<= lg; i++) {
1.234     brouard  1984:     if  (s[i] == occ ) j++;
1.126     brouard  1985:   }
                   1986:   return j;
                   1987: }
                   1988: 
1.349     brouard  1989: int nboccstr(char *textin, char *chain)
                   1990: {
                   1991:   /* Counts the number of occurence of "chain"  in string textin */
                   1992:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1993:   char *strloc;
                   1994:   
                   1995:   int i,j=0;
                   1996: 
                   1997:   i=0;
                   1998: 
                   1999:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   2000:   for(;;) {
                   2001:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   2002:     if(strloc != NULL){
                   2003:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   2004:       j++;
                   2005:     }else
                   2006:       break;
                   2007:   }
                   2008:   return j;
                   2009:   
                   2010: }
1.137     brouard  2011: /* void cutv(char *u,char *v, char*t, char occ) */
                   2012: /* { */
                   2013: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   2014: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   2015: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   2016: /*   int i,lg,j,p=0; */
                   2017: /*   i=0; */
                   2018: /*   lg=strlen(t); */
                   2019: /*   for(j=0; j<=lg-1; j++) { */
                   2020: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   2021: /*   } */
1.126     brouard  2022: 
1.137     brouard  2023: /*   for(j=0; j<p; j++) { */
                   2024: /*     (u[j] = t[j]); */
                   2025: /*   } */
                   2026: /*      u[p]='\0'; */
1.126     brouard  2027: 
1.137     brouard  2028: /*    for(j=0; j<= lg; j++) { */
                   2029: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   2030: /*   } */
                   2031: /* } */
1.126     brouard  2032: 
1.160     brouard  2033: #ifdef _WIN32
                   2034: char * strsep(char **pp, const char *delim)
                   2035: {
                   2036:   char *p, *q;
                   2037:          
                   2038:   if ((p = *pp) == NULL)
                   2039:     return 0;
                   2040:   if ((q = strpbrk (p, delim)) != NULL)
                   2041:   {
                   2042:     *pp = q + 1;
                   2043:     *q = '\0';
                   2044:   }
                   2045:   else
                   2046:     *pp = 0;
                   2047:   return p;
                   2048: }
                   2049: #endif
                   2050: 
1.126     brouard  2051: /********************** nrerror ********************/
                   2052: 
                   2053: void nrerror(char error_text[])
                   2054: {
                   2055:   fprintf(stderr,"ERREUR ...\n");
                   2056:   fprintf(stderr,"%s\n",error_text);
                   2057:   exit(EXIT_FAILURE);
                   2058: }
                   2059: /*********************** vector *******************/
                   2060: double *vector(int nl, int nh)
                   2061: {
                   2062:   double *v;
                   2063:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2064:   if (!v) nrerror("allocation failure in vector");
                   2065:   return v-nl+NR_END;
                   2066: }
                   2067: 
                   2068: /************************ free vector ******************/
                   2069: void free_vector(double*v, int nl, int nh)
                   2070: {
                   2071:   free((FREE_ARG)(v+nl-NR_END));
                   2072: }
                   2073: 
                   2074: /************************ivector *******************************/
                   2075: int *ivector(long nl,long nh)
                   2076: {
                   2077:   int *v;
                   2078:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2079:   if (!v) nrerror("allocation failure in ivector");
                   2080:   return v-nl+NR_END;
                   2081: }
                   2082: 
                   2083: /******************free ivector **************************/
                   2084: void free_ivector(int *v, long nl, long nh)
                   2085: {
                   2086:   free((FREE_ARG)(v+nl-NR_END));
                   2087: }
                   2088: 
                   2089: /************************lvector *******************************/
                   2090: long *lvector(long nl,long nh)
                   2091: {
                   2092:   long *v;
                   2093:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2094:   if (!v) nrerror("allocation failure in ivector");
                   2095:   return v-nl+NR_END;
                   2096: }
                   2097: 
                   2098: /******************free lvector **************************/
                   2099: void free_lvector(long *v, long nl, long nh)
                   2100: {
                   2101:   free((FREE_ARG)(v+nl-NR_END));
                   2102: }
                   2103: 
                   2104: /******************* imatrix *******************************/
                   2105: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2106:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2107: { 
                   2108:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2109:   int **m; 
                   2110:   
                   2111:   /* allocate pointers to rows */ 
                   2112:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2113:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2114:   m += NR_END; 
                   2115:   m -= nrl; 
                   2116:   
                   2117:   
                   2118:   /* allocate rows and set pointers to them */ 
                   2119:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2120:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2121:   m[nrl] += NR_END; 
                   2122:   m[nrl] -= ncl; 
                   2123:   
                   2124:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2125:   
                   2126:   /* return pointer to array of pointers to rows */ 
                   2127:   return m; 
                   2128: } 
                   2129: 
                   2130: /****************** free_imatrix *************************/
                   2131: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2132:       int **m;
                   2133:       long nch,ncl,nrh,nrl; 
                   2134:      /* free an int matrix allocated by imatrix() */ 
                   2135: { 
                   2136:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2137:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2138: } 
                   2139: 
                   2140: /******************* matrix *******************************/
                   2141: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2142: {
                   2143:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2144:   double **m;
                   2145: 
                   2146:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2147:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2148:   m += NR_END;
                   2149:   m -= nrl;
                   2150: 
                   2151:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2152:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2153:   m[nrl] += NR_END;
                   2154:   m[nrl] -= ncl;
                   2155: 
                   2156:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2157:   return m;
1.145     brouard  2158:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2159: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2160: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2161:    */
                   2162: }
                   2163: 
                   2164: /*************************free matrix ************************/
                   2165: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2166: {
                   2167:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2168:   free((FREE_ARG)(m+nrl-NR_END));
                   2169: }
                   2170: 
                   2171: /******************* ma3x *******************************/
                   2172: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2173: {
                   2174:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2175:   double ***m;
                   2176: 
                   2177:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2178:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2179:   m += NR_END;
                   2180:   m -= nrl;
                   2181: 
                   2182:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2183:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2184:   m[nrl] += NR_END;
                   2185:   m[nrl] -= ncl;
                   2186: 
                   2187:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2188: 
                   2189:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2190:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2191:   m[nrl][ncl] += NR_END;
                   2192:   m[nrl][ncl] -= nll;
                   2193:   for (j=ncl+1; j<=nch; j++) 
                   2194:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2195:   
                   2196:   for (i=nrl+1; i<=nrh; i++) {
                   2197:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2198:     for (j=ncl+1; j<=nch; j++) 
                   2199:       m[i][j]=m[i][j-1]+nlay;
                   2200:   }
                   2201:   return m; 
                   2202:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2203:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2204:   */
                   2205: }
                   2206: 
                   2207: /*************************free ma3x ************************/
                   2208: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2209: {
                   2210:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2211:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2212:   free((FREE_ARG)(m+nrl-NR_END));
                   2213: }
                   2214: 
                   2215: /*************** function subdirf ***********/
                   2216: char *subdirf(char fileres[])
                   2217: {
                   2218:   /* Caution optionfilefiname is hidden */
                   2219:   strcpy(tmpout,optionfilefiname);
                   2220:   strcat(tmpout,"/"); /* Add to the right */
                   2221:   strcat(tmpout,fileres);
                   2222:   return tmpout;
                   2223: }
                   2224: 
                   2225: /*************** function subdirf2 ***********/
                   2226: char *subdirf2(char fileres[], char *preop)
                   2227: {
1.314     brouard  2228:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2229:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2230:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2231:   /* Caution optionfilefiname is hidden */
                   2232:   strcpy(tmpout,optionfilefiname);
                   2233:   strcat(tmpout,"/");
                   2234:   strcat(tmpout,preop);
                   2235:   strcat(tmpout,fileres);
                   2236:   return tmpout;
                   2237: }
                   2238: 
                   2239: /*************** function subdirf3 ***********/
                   2240: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2241: {
                   2242:   
                   2243:   /* Caution optionfilefiname is hidden */
                   2244:   strcpy(tmpout,optionfilefiname);
                   2245:   strcat(tmpout,"/");
                   2246:   strcat(tmpout,preop);
                   2247:   strcat(tmpout,preop2);
                   2248:   strcat(tmpout,fileres);
                   2249:   return tmpout;
                   2250: }
1.213     brouard  2251:  
                   2252: /*************** function subdirfext ***********/
                   2253: char *subdirfext(char fileres[], char *preop, char *postop)
                   2254: {
                   2255:   
                   2256:   strcpy(tmpout,preop);
                   2257:   strcat(tmpout,fileres);
                   2258:   strcat(tmpout,postop);
                   2259:   return tmpout;
                   2260: }
1.126     brouard  2261: 
1.213     brouard  2262: /*************** function subdirfext3 ***********/
                   2263: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2264: {
                   2265:   
                   2266:   /* Caution optionfilefiname is hidden */
                   2267:   strcpy(tmpout,optionfilefiname);
                   2268:   strcat(tmpout,"/");
                   2269:   strcat(tmpout,preop);
                   2270:   strcat(tmpout,fileres);
                   2271:   strcat(tmpout,postop);
                   2272:   return tmpout;
                   2273: }
                   2274:  
1.162     brouard  2275: char *asc_diff_time(long time_sec, char ascdiff[])
                   2276: {
                   2277:   long sec_left, days, hours, minutes;
                   2278:   days = (time_sec) / (60*60*24);
                   2279:   sec_left = (time_sec) % (60*60*24);
                   2280:   hours = (sec_left) / (60*60) ;
                   2281:   sec_left = (sec_left) %(60*60);
                   2282:   minutes = (sec_left) /60;
                   2283:   sec_left = (sec_left) % (60);
                   2284:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2285:   return ascdiff;
                   2286: }
                   2287: 
1.126     brouard  2288: /***************** f1dim *************************/
                   2289: extern int ncom; 
                   2290: extern double *pcom,*xicom;
                   2291: extern double (*nrfunc)(double []); 
                   2292:  
                   2293: double f1dim(double x) 
                   2294: { 
                   2295:   int j; 
                   2296:   double f;
                   2297:   double *xt; 
                   2298:  
                   2299:   xt=vector(1,ncom); 
                   2300:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2301:   f=(*nrfunc)(xt); 
                   2302:   free_vector(xt,1,ncom); 
                   2303:   return f; 
                   2304: } 
                   2305: 
                   2306: /*****************brent *************************/
                   2307: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2308: {
                   2309:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2310:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2311:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2312:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2313:    * returned function value. 
                   2314:   */
1.126     brouard  2315:   int iter; 
                   2316:   double a,b,d,etemp;
1.159     brouard  2317:   double fu=0,fv,fw,fx;
1.164     brouard  2318:   double ftemp=0.;
1.126     brouard  2319:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2320:   double e=0.0; 
                   2321:  
                   2322:   a=(ax < cx ? ax : cx); 
                   2323:   b=(ax > cx ? ax : cx); 
                   2324:   x=w=v=bx; 
                   2325:   fw=fv=fx=(*f)(x); 
                   2326:   for (iter=1;iter<=ITMAX;iter++) { 
                   2327:     xm=0.5*(a+b); 
                   2328:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2329:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2330:     printf(".");fflush(stdout);
                   2331:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2332: #ifdef DEBUGBRENT
1.126     brouard  2333:     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);
                   2334:     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);
                   2335:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2336: #endif
                   2337:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2338:       *xmin=x; 
                   2339:       return fx; 
                   2340:     } 
                   2341:     ftemp=fu;
                   2342:     if (fabs(e) > tol1) { 
                   2343:       r=(x-w)*(fx-fv); 
                   2344:       q=(x-v)*(fx-fw); 
                   2345:       p=(x-v)*q-(x-w)*r; 
                   2346:       q=2.0*(q-r); 
                   2347:       if (q > 0.0) p = -p; 
                   2348:       q=fabs(q); 
                   2349:       etemp=e; 
                   2350:       e=d; 
                   2351:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2352:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2353:       else { 
1.224     brouard  2354:                                d=p/q; 
                   2355:                                u=x+d; 
                   2356:                                if (u-a < tol2 || b-u < tol2) 
                   2357:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2358:       } 
                   2359:     } else { 
                   2360:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2361:     } 
                   2362:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2363:     fu=(*f)(u); 
                   2364:     if (fu <= fx) { 
                   2365:       if (u >= x) a=x; else b=x; 
                   2366:       SHFT(v,w,x,u) 
1.183     brouard  2367:       SHFT(fv,fw,fx,fu) 
                   2368:     } else { 
                   2369:       if (u < x) a=u; else b=u; 
                   2370:       if (fu <= fw || w == x) { 
1.224     brouard  2371:                                v=w; 
                   2372:                                w=u; 
                   2373:                                fv=fw; 
                   2374:                                fw=fu; 
1.183     brouard  2375:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2376:                                v=u; 
                   2377:                                fv=fu; 
1.183     brouard  2378:       } 
                   2379:     } 
1.126     brouard  2380:   } 
                   2381:   nrerror("Too many iterations in brent"); 
                   2382:   *xmin=x; 
                   2383:   return fx; 
                   2384: } 
                   2385: 
                   2386: /****************** mnbrak ***********************/
                   2387: 
                   2388: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2389:            double (*func)(double)) 
1.183     brouard  2390: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2391: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2392: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2393: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2394:    */
1.126     brouard  2395:   double ulim,u,r,q, dum;
                   2396:   double fu; 
1.187     brouard  2397: 
                   2398:   double scale=10.;
                   2399:   int iterscale=0;
                   2400: 
                   2401:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2402:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2403: 
                   2404: 
                   2405:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2406:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2407:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2408:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2409:   /* } */
                   2410: 
1.126     brouard  2411:   if (*fb > *fa) { 
                   2412:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2413:     SHFT(dum,*fb,*fa,dum) 
                   2414:   } 
1.126     brouard  2415:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2416:   *fc=(*func)(*cx); 
1.183     brouard  2417: #ifdef DEBUG
1.224     brouard  2418:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2419:   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  2420: #endif
1.224     brouard  2421:   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  2422:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2423:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2424:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2425:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2426:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2427:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2428:       fu=(*func)(u); 
1.163     brouard  2429: #ifdef DEBUG
                   2430:       /* f(x)=A(x-u)**2+f(u) */
                   2431:       double A, fparabu; 
                   2432:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2433:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2434:       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);
                   2435:       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  2436:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2437:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2438:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2439:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2440: #endif 
1.184     brouard  2441: #ifdef MNBRAKORIGINAL
1.183     brouard  2442: #else
1.191     brouard  2443: /*       if (fu > *fc) { */
                   2444: /* #ifdef DEBUG */
                   2445: /*       printf("mnbrak4  fu > fc \n"); */
                   2446: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2447: /* #endif */
                   2448: /*     /\* 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 *\\/  *\/ */
                   2449: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2450: /*     dum=u; /\* Shifting c and u *\/ */
                   2451: /*     u = *cx; */
                   2452: /*     *cx = dum; */
                   2453: /*     dum = fu; */
                   2454: /*     fu = *fc; */
                   2455: /*     *fc =dum; */
                   2456: /*       } else { /\* end *\/ */
                   2457: /* #ifdef DEBUG */
                   2458: /*       printf("mnbrak3  fu < fc \n"); */
                   2459: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2460: /* #endif */
                   2461: /*     dum=u; /\* Shifting c and u *\/ */
                   2462: /*     u = *cx; */
                   2463: /*     *cx = dum; */
                   2464: /*     dum = fu; */
                   2465: /*     fu = *fc; */
                   2466: /*     *fc =dum; */
                   2467: /*       } */
1.224     brouard  2468: #ifdef DEBUGMNBRAK
                   2469:                 double A, fparabu; 
                   2470:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2471:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2472:      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);
                   2473:      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  2474: #endif
1.191     brouard  2475:       dum=u; /* Shifting c and u */
                   2476:       u = *cx;
                   2477:       *cx = dum;
                   2478:       dum = fu;
                   2479:       fu = *fc;
                   2480:       *fc =dum;
1.183     brouard  2481: #endif
1.162     brouard  2482:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2483: #ifdef DEBUG
1.224     brouard  2484:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2485:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2486: #endif
1.126     brouard  2487:       fu=(*func)(u); 
                   2488:       if (fu < *fc) { 
1.183     brouard  2489: #ifdef DEBUG
1.224     brouard  2490:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2491:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2492: #endif
                   2493:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2494:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2495: #ifdef DEBUG
                   2496:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2497: #endif
                   2498:       } 
1.162     brouard  2499:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2500: #ifdef DEBUG
1.224     brouard  2501:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2502:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2503: #endif
1.126     brouard  2504:       u=ulim; 
                   2505:       fu=(*func)(u); 
1.183     brouard  2506:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2507: #ifdef DEBUG
1.224     brouard  2508:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2509:       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  2510: #endif
1.126     brouard  2511:       u=(*cx)+GOLD*(*cx-*bx); 
                   2512:       fu=(*func)(u); 
1.224     brouard  2513: #ifdef DEBUG
                   2514:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2515:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2516: #endif
1.183     brouard  2517:     } /* end tests */
1.126     brouard  2518:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2519:     SHFT(*fa,*fb,*fc,fu) 
                   2520: #ifdef DEBUG
1.224     brouard  2521:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2522:       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  2523: #endif
                   2524:   } /* 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  2525: } 
                   2526: 
                   2527: /*************** linmin ************************/
1.162     brouard  2528: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2529: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2530: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2531: the value of func at the returned location p . This is actually all accomplished by calling the
                   2532: routines mnbrak and brent .*/
1.126     brouard  2533: int ncom; 
                   2534: double *pcom,*xicom;
                   2535: double (*nrfunc)(double []); 
                   2536:  
1.224     brouard  2537: #ifdef LINMINORIGINAL
1.126     brouard  2538: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2539: #else
                   2540: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2541: #endif
1.126     brouard  2542: { 
                   2543:   double brent(double ax, double bx, double cx, 
                   2544:               double (*f)(double), double tol, double *xmin); 
                   2545:   double f1dim(double x); 
                   2546:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2547:              double *fc, double (*func)(double)); 
                   2548:   int j; 
                   2549:   double xx,xmin,bx,ax; 
                   2550:   double fx,fb,fa;
1.187     brouard  2551: 
1.203     brouard  2552: #ifdef LINMINORIGINAL
                   2553: #else
                   2554:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2555: #endif
                   2556:   
1.126     brouard  2557:   ncom=n; 
                   2558:   pcom=vector(1,n); 
                   2559:   xicom=vector(1,n); 
                   2560:   nrfunc=func; 
                   2561:   for (j=1;j<=n;j++) { 
                   2562:     pcom[j]=p[j]; 
1.202     brouard  2563:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2564:   } 
1.187     brouard  2565: 
1.203     brouard  2566: #ifdef LINMINORIGINAL
                   2567:   xx=1.;
                   2568: #else
                   2569:   axs=0.0;
                   2570:   xxs=1.;
                   2571:   do{
                   2572:     xx= xxs;
                   2573: #endif
1.187     brouard  2574:     ax=0.;
                   2575:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2576:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2577:     /* 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))   */
                   2578:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2579:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2580:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2581:     /* 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  2582: #ifdef LINMINORIGINAL
                   2583: #else
                   2584:     if (fx != fx){
1.224     brouard  2585:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2586:                        printf("|");
                   2587:                        fprintf(ficlog,"|");
1.203     brouard  2588: #ifdef DEBUGLINMIN
1.224     brouard  2589:                        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  2590: #endif
                   2591:     }
1.224     brouard  2592:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2593: #endif
                   2594:   
1.191     brouard  2595: #ifdef DEBUGLINMIN
                   2596:   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  2597:   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  2598: #endif
1.224     brouard  2599: #ifdef LINMINORIGINAL
                   2600: #else
1.317     brouard  2601:   if(fb == fx){ /* Flat function in the direction */
                   2602:     xmin=xx;
1.224     brouard  2603:     *flat=1;
1.317     brouard  2604:   }else{
1.224     brouard  2605:     *flat=0;
                   2606: #endif
                   2607:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2608:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2609:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2610:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2611:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2612:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2613: #ifdef DEBUG
1.224     brouard  2614:   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);
                   2615:   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);
                   2616: #endif
                   2617: #ifdef LINMINORIGINAL
                   2618: #else
                   2619:                        }
1.126     brouard  2620: #endif
1.191     brouard  2621: #ifdef DEBUGLINMIN
                   2622:   printf("linmin end ");
1.202     brouard  2623:   fprintf(ficlog,"linmin end ");
1.191     brouard  2624: #endif
1.126     brouard  2625:   for (j=1;j<=n;j++) { 
1.203     brouard  2626: #ifdef LINMINORIGINAL
                   2627:     xi[j] *= xmin; 
                   2628: #else
                   2629: #ifdef DEBUGLINMIN
                   2630:     if(xxs <1.0)
                   2631:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2632: #endif
                   2633:     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) */
                   2634: #ifdef DEBUGLINMIN
                   2635:     if(xxs <1.0)
                   2636:       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 );
                   2637: #endif
                   2638: #endif
1.187     brouard  2639:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2640:   } 
1.191     brouard  2641: #ifdef DEBUGLINMIN
1.203     brouard  2642:   printf("\n");
1.191     brouard  2643:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2644:   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  2645:   for (j=1;j<=n;j++) { 
1.202     brouard  2646:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2647:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2648:     if(j % ncovmodel == 0){
1.191     brouard  2649:       printf("\n");
1.202     brouard  2650:       fprintf(ficlog,"\n");
                   2651:     }
1.191     brouard  2652:   }
1.203     brouard  2653: #else
1.191     brouard  2654: #endif
1.126     brouard  2655:   free_vector(xicom,1,n); 
                   2656:   free_vector(pcom,1,n); 
                   2657: } 
                   2658: 
1.359     brouard  2659: /**** praxis gegen ****/
                   2660: 
                   2661: /* This has been tested by Visual C from Microsoft and works */
                   2662: /* meaning tha valgrind could be wrong */
                   2663: /*********************************************************************/
                   2664: /*     f u n c t i o n     p r a x i s                              */
                   2665: /*                                                                   */
                   2666: /* praxis is a general purpose routine for the minimization of a     */
                   2667: /* function in several variables. the algorithm used is a modifi-    */
                   2668: /* cation of conjugate gradient search method by powell. the changes */
                   2669: /* are due to r.p. brent, who gives an algol-w program, which served */
                   2670: /* as a basis for this function.                                     */
                   2671: /*                                                                   */
                   2672: /* references:                                                       */
                   2673: /*     - powell, m.j.d., 1964. an efficient method for finding       */
                   2674: /*       the minimum of a function in several variables without      */
                   2675: /*       calculating derivatives, computer journal, 7, 155-162       */
                   2676: /*     - brent, r.p., 1973. algorithms for minimization without      */
                   2677: /*       derivatives, prentice hall, englewood cliffs.               */
                   2678: /*                                                                   */
                   2679: /*     problems, suggestions or improvements are always wellcome     */
                   2680: /*                       karl gegenfurtner   07/08/87                */
                   2681: /*                                           c - version             */
                   2682: /*********************************************************************/
                   2683: /*                                                                   */
                   2684: /* usage: min = praxis(tol, macheps, h, n, prin, x, func)      */
                   2685: /* macheps has been suppressed because it is replaced by DBL_EPSILON */
                   2686: /* and if it was an argument of praxis (as it is in original brent)  */
                   2687: /* it should be declared external */
                   2688: /* usage: min = praxis(tol, h, n, prin, x, func)      */
                   2689: /* was    min = praxis(fun, x, n);                                   */
                   2690: /*                                                                   */
                   2691: /*  fun        the function to be minimized. fun is called from      */
                   2692: /*             praxis with x and n as arguments                      */
                   2693: /*  x          a double array containing the initial guesses for     */
                   2694: /*             the minimum, which will contain the solution on       */
                   2695: /*             return                                                */
                   2696: /*  n          an integer specifying the number of unknown           */
                   2697: /*             parameters                                            */
                   2698: /*  min        praxis returns the least calculated value of fun      */
                   2699: /*                                                                   */
                   2700: /* some additional global variables control some more aspects of     */
                   2701: /* the inner workings of praxis. setting them is optional, they      */
                   2702: /* are all set to some reasonable default values given below.        */
                   2703: /*                                                                   */
                   2704: /*   prin      controls the printed output from the routine.         */
                   2705: /*             0 -> no output                                        */
                   2706: /*             1 -> print only starting and final values             */
                   2707: /*             2 -> detailed map of the minimization process         */
                   2708: /*             3 -> print also eigenvalues and vectors of the        */
                   2709: /*                  search directions                                */
                   2710: /*             the default value is 1                                */
                   2711: /*  tol        is the tolerance allowed for the precision of the     */
                   2712: /*             solution. praxis returns if the criterion             */
                   2713: /*             2 * ||x[k]-x[k-1]|| <= sqrt(macheps) * ||x[k]|| + tol */
                   2714: /*             is fulfilled more than ktm times.                     */
                   2715: /*             the default value depends on the machine precision    */
                   2716: /*  ktm        see just above. default is 1, and a value of 4 leads  */
                   2717: /*             to a very(!) cautious stopping criterion.             */
                   2718: /*  h0 or step       is a steplength parameter and should be set equal     */
                   2719: /*             to the expected distance from the solution.           */
                   2720: /*             exceptionally small or large values of step lead to   */
                   2721: /*             slower convergence on the first few iterations        */
                   2722: /*             the default value for step is 1.0                     */
                   2723: /*  scbd       is a scaling parameter. 1.0 is the default and        */
                   2724: /*             indicates no scaling. if the scales for the different */
                   2725: /*             parameters are very different, scbd should be set to  */
                   2726: /*             a value of about 10.0.                                */
                   2727: /*  illc       should be set to true (1) if the problem is known to  */
                   2728: /*             be ill-conditioned. the default is false (0). this    */
                   2729: /*             variable is automatically set, when praxis finds      */
                   2730: /*             the problem to be ill-conditioned during iterations.  */
                   2731: /*  maxfun     is the maximum number of calls to fun allowed. praxis */
                   2732: /*             will return after maxfun calls to fun even when the   */
                   2733: /*             minimum is not yet found. the default value of 0      */
                   2734: /*             indicates no limit on the number of calls.            */
                   2735: /*             this return condition is only checked every n         */
                   2736: /*             iterations.                                           */
                   2737: /*                                                                   */
                   2738: /*********************************************************************/
                   2739: 
                   2740: #include <math.h>
                   2741: #include <stdio.h>
                   2742: #include <stdlib.h>
                   2743: #include <float.h> /* for DBL_EPSILON */
                   2744: /* #include "machine.h" */
                   2745: 
                   2746: 
                   2747: /* extern void minfit(int n, double eps, double tol, double **ab, double q[]); */
                   2748: /* extern void minfit(int n, double eps, double tol, double ab[N][N], double q[]); */
                   2749: /* control parameters */
                   2750: /* control parameters */
                   2751: #define SQREPSILON 1.0e-19
                   2752: /* #define EPSILON 1.0e-8 */ /* in main */
                   2753: 
                   2754: double tol = SQREPSILON,
                   2755:        scbd = 1.0,
                   2756:        step = 1.0;
                   2757: int    ktm = 1,
                   2758:        /* prin = 2, */
                   2759:        maxfun = 0,
                   2760:        illc = 0;
                   2761:        
                   2762: /* some global variables */
                   2763: static int i, j, k, k2, nl, nf, kl, kt;
                   2764: /* static double s; */
                   2765: double sl, dn, dmin,
                   2766:        fx, f1, lds, ldt, sf, df,
                   2767:        qf1, qd0, qd1, qa, qb, qc,
                   2768:        m2, m4, small_windows, vsmall, large, 
                   2769:        vlarge, ldfac, t2;
                   2770: /* static double d[N], y[N], z[N], */
                   2771: /*        q0[N], q1[N], v[N][N]; */
                   2772: 
                   2773: static double *d, *y, *z;
                   2774: static double  *q0, *q1, **v;
                   2775: double *tflin; /* used in flin: return (*fun)(tflin, n); */
                   2776: double *e; /* used in minfit, don't konw how to free memory and thus made global */
                   2777: /* static double s, sl, dn, dmin, */
                   2778: /*        fx, f1, lds, ldt, sf, df, */
                   2779: /*        qf1, qd0, qd1, qa, qb, qc, */
                   2780: /*        m2, m4, small, vsmall, large,  */
                   2781: /*        vlarge, ldfac, t2; */
                   2782: /* static double d[N], y[N], z[N], */
                   2783: /*        q0[N], q1[N], v[N][N]; */
                   2784: 
                   2785: /* these will be set by praxis to point to it's arguments */
                   2786: static int prin; /* added */
                   2787: static int n;
                   2788: static double *x;
                   2789: static double (*fun)();
                   2790: /* static double (*fun)(double *x, int n); */
                   2791: 
                   2792: /* these will be set by praxis to the global control parameters */
                   2793: /* static double h, macheps, t; */
                   2794: extern double macheps;
                   2795: static double h;
                   2796: static double t;
                   2797: 
                   2798: static double 
                   2799: drandom()      /* return random no between 0 and 1 */
                   2800: {
                   2801:    return (double)(rand()%(8192*2))/(double)(8192*2);
                   2802: }
                   2803: 
                   2804: static void sort()             /* d and v in descending order */
                   2805: {
                   2806:    int k, i, j;
                   2807:    double s;
                   2808: 
                   2809:    for (i=1; i<=n-1; i++) {
                   2810:        k = i; s = d[i];
                   2811:        for (j=i+1; j<=n; j++) {
                   2812:            if (d[j] > s) {
                   2813:              k = j;
                   2814:              s = d[j];
                   2815:           }
                   2816:        }
                   2817:        if (k > i) {
                   2818:          d[k] = d[i];
                   2819:          d[i] = s;
                   2820:          for (j=1; j<=n; j++) {
                   2821:              s = v[j][i];
                   2822:              v[j][i] = v[j][k];
                   2823:              v[j][k] = s;
                   2824:          }
                   2825:        }
                   2826:    }
                   2827: }
                   2828: 
                   2829: double randbrent ( int *naught )
                   2830: {
                   2831:   double ran1, ran3[127], half;
                   2832:   int ran2, q, r, i, j;
                   2833:   int init=0; /* false */
                   2834:   double rr;
                   2835:   /* REAL*8 RAN1,RAN3(127),HALF */
                   2836: 
                   2837:   /*     INTEGER RAN2,Q,R */
                   2838:   /*     LOGICAL INIT */
                   2839:   /*     DATA INIT/.FALSE./ */
                   2840:   /*     IF (INIT) GO TO 3 */
                   2841:   if(!init){ 
                   2842: /*       R = MOD(NAUGHT,8190) + 1 *//* 1804289383 rand () */
                   2843:     r = *naught % 8190 + 1;/* printf(" naught r %d %d",*naught,r); */
                   2844:     ran2=127;
                   2845:     for(i=ran2; i>0; i--){
                   2846: /*       RAN2 = 128 */
                   2847: /*       DO 2 I=1,127 */
                   2848:       ran2 = ran2-1;
                   2849: /*          RAN2 = RAN2 - 1 */
                   2850:       ran1 = -pow(2.0,55);
                   2851: /*          RAN1 = -2.D0**55 */
                   2852: /*          DO 1 J=1,7 */
                   2853:       for(j=1; j<=7;j++){
                   2854: /*             R = MOD(1756*R,8191) */
                   2855:        r = (1756*r) % 8191;/* printf(" i=%d (1756*r)%8191=%d",j,r); */
                   2856:        q=r/32;
                   2857: /*             Q = R/32 */
                   2858: /* 1           RAN1 = (RAN1 + Q)*(1.0D0/256) */
                   2859:        ran1 =(ran1+q)*(1.0/256);
                   2860:       }
                   2861: /* 2        RAN3(RAN2) = RAN1 */
                   2862:       ran3[ran2] = ran1; /* printf(" ran2=%d ran1=%.7g \n",ran2,ran1); */ 
                   2863:     }
                   2864: /*       INIT = .TRUE. */
                   2865:     init=1;
                   2866: /* 3     IF (RAN2.EQ.1) RAN2 = 128 */
                   2867:   }
                   2868:   if(ran2 == 0) ran2 = 126;
                   2869:   else ran2 = ran2 -1;
                   2870:   /* RAN2 = RAN2 - 1 */
                   2871:   /* RAN1 = RAN1 + RAN3(RAN2) */
                   2872:   ran1 = ran1 + ran3[ran2];/* printf("BIS ran2=%d ran1=%.7g \n",ran2,ran1);  */
                   2873:   half= 0.5;
                   2874:   /* HALF = .5D0 */
                   2875:   /* IF (RAN1.GE.0.D0) HALF = -HALF */
                   2876:   if(ran1 >= 0.) half =-half;
                   2877:   ran1 = ran1 +half;
                   2878:   ran3[ran2] = ran1;
                   2879:   rr= ran1+0.5;
                   2880:   /* RAN1 = RAN1 + HALF */
                   2881:   /*   RAN3(RAN2) = RAN1 */
                   2882:   /*   RANDOM = RAN1 + .5D0 */
                   2883: /*   r = ( ( double ) ( *seed ) ) * 4.656612875E-10; */
                   2884:   return rr;
                   2885: }
                   2886: static void matprint(char *s, double **v, int m, int n)
                   2887: /* char *s; */
                   2888: /* double v[N][N]; */
                   2889: {
                   2890: #define INCX 8
                   2891:   int i;
                   2892:  
                   2893:   int i2hi;
                   2894:   int ihi;
                   2895:   int ilo;
                   2896:   int i2lo;
                   2897:   int jlo=1;
                   2898:   int j;
                   2899:   int j2hi;
                   2900:   int jhi;
                   2901:   int j2lo;
                   2902:   ilo=1;
                   2903:   ihi=n;
                   2904:   jlo=1;
                   2905:   jhi=n;
                   2906:   
                   2907:   printf ("\n" );
                   2908:   printf ("%s\n", s );
                   2909:   for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
                   2910:   {
                   2911:     j2hi = j2lo + INCX - 1;
                   2912:     if ( n < j2hi )
                   2913:     {
                   2914:       j2hi = n;
                   2915:     }
                   2916:     if ( jhi < j2hi )
                   2917:     {
                   2918:       j2hi = jhi;
                   2919:     }
                   2920: 
                   2921:     /* fprintf ( ficlog, "\n" ); */
                   2922:     printf ("\n" );
                   2923: /*
                   2924:   For each column J in the current range...
                   2925: 
                   2926:   Write the header.
                   2927: */
                   2928:     /* fprintf ( ficlog, "  Col:  "); */
                   2929:     printf ("Col:");
                   2930:     for ( j = j2lo; j <= j2hi; j++ )
                   2931:     {
                   2932:       /* fprintf ( ficlog, "  %7d     ", j - 1 ); */
                   2933:       /* printf (" %9d      ", j - 1 ); */
                   2934:       printf (" %9d      ", j );
                   2935:     }
                   2936:     /* fprintf ( ficlog, "\n" ); */
                   2937:     /* fprintf ( ficlog, "  Row\n" ); */
                   2938:     /* fprintf ( ficlog, "\n" ); */
                   2939:     printf ("\n" );
                   2940:     printf ("  Row\n" );
                   2941:     printf ("\n" );
                   2942: /*
                   2943:   Determine the range of the rows in this strip.
                   2944: */
                   2945:     if ( 1 < ilo ){
                   2946:       i2lo = ilo;
                   2947:     }else{
                   2948:       i2lo = 1;
                   2949:     }
                   2950:     if ( m < ihi ){
                   2951:       i2hi = m;
                   2952:     }else{
                   2953:       i2hi = ihi;
                   2954:     }
                   2955: 
                   2956:     for ( i = i2lo; i <= i2hi; i++ ){
                   2957: /*
                   2958:   Print out (up to) 5 entries in row I, that lie in the current strip.
                   2959: */
                   2960:       /* fprintf ( ficlog, "%5d:", i - 1 ); */
                   2961:       /* printf ("%5d:", i - 1 ); */
                   2962:       printf ("%5d:", i );
                   2963:       for ( j = j2lo; j <= j2hi; j++ )
                   2964:       {
                   2965:         /* fprintf ( ficlog, "  %14g", a[i-1+(j-1)*m] ); */
                   2966:         /* printf ("%14.7g  ", a[i-1+(j-1)*m] ); */
                   2967:            /* printf("%14.7f  ", v[i-1][j-1]); */
                   2968:            printf("%14.7f  ", v[i][j]);
                   2969:         /* fprintf ( stdout, "  %14g", a[i-1+(j-1)*m] ); */
                   2970:       }
                   2971:       /* fprintf ( ficlog, "\n" ); */
                   2972:       printf ("\n" );
                   2973:     }
                   2974:   }
                   2975:  
                   2976:    /* printf("%s\n", s); */
                   2977:    /* for (k=0; k<n; k++) { */
                   2978:    /*     for (i=0; i<n; i++) { */
                   2979:    /*         /\* printf("%20.10e ", v[k][i]); *\/ */
                   2980:    /*     } */
                   2981:    /*     printf("\n"); */
                   2982:    /* } */
                   2983: #undef INCX  
                   2984: }
                   2985: 
                   2986: void vecprint(char *s, double *x, int n)
                   2987: /* char *s; */
                   2988: /* double x[N]; */
                   2989: {
                   2990:    int i=0;
                   2991:    
                   2992:    printf(" %s", s);
                   2993:    /* for (i=0; i<n; i++) */
                   2994:    for (i=1; i<=n; i++)
                   2995:      printf ("  %14.7g",  x[i] );
                   2996:      /* printf("  %8d: %14g\n", i, x[i]); */
                   2997:    printf ("\n" ); 
                   2998: }
                   2999: 
                   3000: static void print()            /* print a line of traces */
                   3001: {
                   3002:  
                   3003: 
                   3004:    printf("\n");
                   3005:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   3006:    /* printf("... after %u function calls ...\n", nf); */
                   3007:    /* printf("... including %u linear searches ...\n", nl); */
                   3008:    printf("%10d    %10d%14.7g",nl, nf, fx);
                   3009:    vecprint("... current values of x ...", x, n);
                   3010: }
                   3011: /* static void print2(int n, double *x, int prin, double fx, int nf, int nl) */ /* print a line of traces */
                   3012: static void print2() /* print a line of traces */
                   3013: {
                   3014:   int i; double fmin=0.;
                   3015: 
                   3016:    /* printf("\n"); */
                   3017:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   3018:    /* printf("... after %u function calls ...\n", nf); */
                   3019:    /* printf("... including %u linear searches ...\n", nl); */
                   3020:    /* printf("%10d    %10d%14.7g",nl, nf, fx); */
1.363   ! brouard  3021:   /* printf ( "\n" ); */
1.359     brouard  3022:   printf ( "  Linear searches      %d", nl );
                   3023:   /* printf ( "  Linear searches      %d\n", nl ); */
                   3024:   /* printf ( "  Function evaluations %d\n", nf ); */
                   3025:   /* printf ( "  Function value FX = %g\n", fx ); */
                   3026:   printf ( "  Function evaluations %d", nf );
                   3027:   printf ( "  Function value FX = %.12lf\n", fx );
1.363   ! brouard  3028:   fprintf (ficlog, "  Function evaluations %d", nf );
        !          3029:   fprintf (ficlog, "  Function value FX = %.12lf\n", fx );
1.359     brouard  3030: #ifdef DEBUGPRAX
                   3031:    printf("n=%d prin=%d\n",n,prin);
                   3032: #endif
1.363   ! brouard  3033:    /* if(fx <= fmin) printf(" UNDEFINED "); else  printf("%14.7g",log(fx-fmin)); */
1.359     brouard  3034:    if ( n <= 4 || 2 < prin )
                   3035:    {
                   3036:      /* for(i=1;i<=n;i++)printf("%14.7g",x[i-1]); */
1.363   ! brouard  3037:      for(i=1;i<=n;i++){
        !          3038:        printf("%14.7g",x[i]);
        !          3039:        fprintf(ficlog,"%14.7g",x[i]);
        !          3040:      }
1.359     brouard  3041:      /* r8vec_print ( n, x, "  X:" ); */
                   3042:    }
                   3043:    printf("\n");
1.363   ! brouard  3044:    fprintf(ficlog,"\n");
1.359     brouard  3045:  }
                   3046: 
                   3047: 
                   3048: /* #ifdef MSDOS */
                   3049: /* static double tflin[N]; */
                   3050: /* #endif */
                   3051: 
                   3052: static double flin(double l, int j)
                   3053: /* double l; */
                   3054: {
                   3055:    int i;
                   3056:    /* #ifndef MSDOS */
                   3057:    /*    double tflin[N]; */
                   3058:    /* #endif    */
                   3059:    /* double *tflin; */ /* Be careful to put tflin on a vector n */
                   3060: 
                   3061:    /* j is used from 0 to n-1 and can be -1 for parabolic search */
                   3062: 
                   3063:    /* if (j != -1) {           /\* linear search *\/ */
                   3064:    if (j > 0) {                /* linear search */
                   3065:      /* for (i=0; i<n; i++){ */
                   3066:      for (i=1; i<=n; i++){
                   3067:           tflin[i] = x[i] + l *v[i][j];
                   3068: #ifdef DEBUGPRAX
                   3069:          /* printf("     flin i=%14d t=%14.7f x=%14.7f l=%14.7f v[%d,%d]=%14.7f nf=%14d\n",i+1, tflin[i],x[i],l,i,j,v[i][j],nf); */
                   3070:          printf("     flin i=%14d t=%14.7f x=%14.7f l=%14.7f v[%d,%d]=%14.7f nf=%14d\n",i, tflin[i],x[i],l,i,j,v[i][j],nf);
                   3071: #endif
                   3072:      }
                   3073:    }
                   3074:    else {                      /* search along parabolic space curve */
                   3075:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3076:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3077:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3078: #ifdef DEBUGPRAX      
                   3079:       printf("     search along a parabolic space curve. j=%14d nf=%14d l=%14.7f qd0=%14.7f qd1=%14.7f\n",j,nf,l,qd0,qd1);
                   3080: #endif
                   3081:       /* for (i=0; i<n; i++){ */
                   3082:       for (i=1; i<=n; i++){
                   3083:           tflin[i] = qa*q0[i]+qb*x[i]+qc*q1[i];
                   3084: #ifdef DEBUGPRAX
                   3085:           /* printf("      parabole i=%14d t(i)=%14.7f q0=%14.7f x=%14.7f q1=%14.7f\n",i+1,tflin[i],q0[i],x[i],q1[i]); */
                   3086:           printf("      parabole i=%14d t(i)=%14.7e q0=%14.7e x=%14.7e q1=%14.7e\n",i,tflin[i],q0[i],x[i],q1[i]);
                   3087: #endif
                   3088:       }
                   3089:    }
                   3090:    nf++;
                   3091: 
                   3092: #ifdef NR_SHIFT
                   3093:       return (*fun)((tflin-1), n);
                   3094: #else
                   3095:      /* return (*fun)(tflin, n);*/
                   3096:       return (*fun)(tflin);
                   3097: #endif
                   3098: }
                   3099: 
                   3100: void minny(int j, int nits, double *d2, double *x1, double f1, int fk)
                   3101: /* double *d2, *x1, f1; */
                   3102: {
                   3103: /* here j is from 0 to n-1 and can be -1 for parabolic search  */
                   3104:   /*      MINIMIZES F FROM X IN THE DIRECTION V(*,J) */
                   3105:           /*      UNLESS J<1, WHEN A QUADRATIC SEARCH IS DONE */
                   3106:           /*      IN THE PLANE DEFINED BY Q0, Q1 AND X. */
                   3107:           /*      D2 AN APPROXIMATION TO HALF F'' (OR ZERO), */
                   3108:           /*      X1 AN ESTIMATE OF DISTANCE TO MINIMUM, */
                   3109:           /*      RETURNED AS THE DISTANCE FOUND. */
                   3110:           /*       IF FK = TRUE THEN F1 IS FLIN(X1), OTHERWISE */
                   3111:           /*       X1 AND F1 ARE IGNORED ON ENTRY UNLESS FINAL */
                   3112:           /*       FX > F1. NITS CONTROLS THE NUMBER OF TIMES */
                   3113:           /*       AN ATTEMPT IS MADE TO HALVE THE INTERVAL. */
                   3114:           /* SIDE EFFECTS: USES AND ALTERS X, FX, NF, NL. */
                   3115:           /*       IF J < 1 USES VARIABLES Q... . */
                   3116:          /*       USES H, N, T, M2, M4, LDT, DMIN, MACHEPS; */
                   3117:    int k, i, dz;
                   3118:    double x2, xm, f0, f2, fm, d1, t2, sf1, sx1;
                   3119:    double s;
                   3120:    double macheps;
                   3121:    macheps=pow(16.0,-13.0);
                   3122:    sf1 = f1; sx1 = *x1;
                   3123:    k = 0; xm = 0.0; fm = f0 = fx; dz = *d2 < macheps;
                   3124:    /* h=1.0;*/ /* To be revised */
                   3125: #ifdef DEBUGPRAX
                   3126:    /* printf("min macheps=%14g h=%14g step=%14g t=%14g fx=%14g\n",macheps,h, step,t, fx);  */
                   3127:    /* Where is fx coming from */
                   3128:    printf("   min macheps=%14g h=%14g  t=%14g fx=%.9lf dirj=%d\n",macheps, h, t, fx, j);
                   3129:    matprint("  min vectors:",v,n,n);
                   3130: #endif
                   3131:    /* find step size */
                   3132:    s = 0.;
                   3133:    /* for (i=0; i<n; i++) s += x[i]*x[i]; */
                   3134:    for (i=1; i<=n; i++) s += x[i]*x[i];
                   3135:    s = sqrt(s);
                   3136:    if (dz)
                   3137:       t2 = m4*sqrt(fabs(fx)/dmin + s*ldt) + m2*ldt;
                   3138:    else
                   3139:       t2 = m4*sqrt(fabs(fx)/(*d2) + s*ldt) + m2*ldt;
                   3140:    s = s*m4 + t;
                   3141:    if (dz && t2 > s) t2 = s;
                   3142:    if (t2 < small_windows) t2 = small_windows;
                   3143:    if (t2 > 0.01*h) t2 = 0.01 * h;
                   3144:    if (fk && f1 <= fm) {
                   3145:       xm = *x1;
                   3146:       fm = f1;
                   3147:    }
                   3148: #ifdef DEBUGPRAX
                   3149:    printf("   additional flin X1=%14.7f t2=%14.7f *f1=%14.7f fm=%14.7f fk=%d\n",*x1,t2,f1,fm,fk);
                   3150: #endif   
                   3151:    if (!fk || fabs(*x1) < t2) {
                   3152:      *x1 = (*x1 >= 0 ? t2 : -t2); 
                   3153:       /* *x1 = (*x1 > 0 ? t2 : -t2); */ /* kind of error */
                   3154: #ifdef DEBUGPRAX
                   3155:      printf("    additional flin X1=%16.10e dirj=%d fk=%d\n",*x1, j, fk);
                   3156: #endif
                   3157:       f1 = flin(*x1, j);
                   3158: #ifdef DEBUGPRAX
                   3159:     printf("    after flin f1=%18.12e dirj=%d fk=%d\n",f1, j,fk);
                   3160: #endif
                   3161:    }
                   3162:    if (f1 <= fm) {
                   3163:       xm = *x1;
                   3164:       fm = f1;
                   3165:    }
                   3166: L0: /*L0 loop or next */
                   3167: /*
                   3168:   Evaluate FLIN at another point and estimate the second derivative.
                   3169: */
                   3170:    if (dz) {
                   3171:       x2 = (f0 < f1 ? -(*x1) : 2*(*x1));
                   3172: #ifdef DEBUGPRAX
                   3173:       printf("     additional second flin x2=%14.8e x1=%14.8e f0=%14.8e f1=%18.12e dirj=%d\n",x2,*x1,f0,f1,j);
                   3174: #endif
                   3175:       f2 = flin(x2, j);
                   3176: #ifdef DEBUGPRAX
                   3177:       printf("     additional second flin x2=%16.10e x1=%16.10e f1=%18.12e f0=%18.10e f2=%18.10e fm=%18.10e\n",x2, *x1, f1,f0,f2,fm);
                   3178: #endif
                   3179:       if (f2 <= fm) {
                   3180:          xm = x2;
                   3181:         fm = f2;
                   3182:       }
                   3183:       /* d2 is the curvature or double difference f1 doesn't seem to be accurately computed */
                   3184:       *d2 = (x2*(f1-f0) - (*x1)*(f2-f0))/((*x1)*x2*((*x1)-x2));
                   3185: #ifdef DEBUGPRAX
                   3186:       double d11,d12;
                   3187:       d11=(f1-f0)/(*x1);d12=(f2-f0)/x2;
                   3188:       printf(" d11=%18.12e d12=%18.12e d11-d12=%18.12e x1-x2=%18.12e (d11-d12)/(x2-(*x1))=%18.12e\n", d11 ,d12, d11-d12, x2-(*x1), (d11-d12)/(x2-(*x1)));
                   3189:       printf(" original computing f1=%18.12e *d2=%16.10e f0=%18.12e f1-f0=%16.10e f2-f0=%16.10e\n",f1,*d2,f0,f1-f0, f2-f0);
                   3190:       double ff1=7.783920622852e+04;
                   3191:       double f1mf0=9.0344736236e-05;
                   3192:       *d2 = (f1mf0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2);
                   3193:       /* *d2 = (ff1-f0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2); */
                   3194:       printf(" simpliff computing *d2=%16.10e f1mf0=%18.12e,f1=f0+f1mf0=%18.12e\n",*d2,f1mf0,f0+f1mf0);
                   3195:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);
                   3196:       printf(" overlifi computing *d2=%16.10e\n",*d2);
                   3197: #endif
                   3198:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);      
                   3199:    }
                   3200: #ifdef DEBUGPRAX
                   3201:       printf("    additional second flin xm=%14.8e fm=%14.8e *d2=%14.8e\n",xm, fm,*d2);
                   3202: #endif
                   3203:    /*
                   3204:      Estimate the first derivative at 0.
                   3205:    */
                   3206:    d1 = (f1-f0)/(*x1) - *x1**d2; dz = 1;
                   3207:    /*
                   3208:       Predict the minimum.
                   3209:     */
                   3210:    if (*d2 <= small_windows) {
                   3211:      x2 = (d1 < 0 ? h : -h);
                   3212:    }
                   3213:    else {
                   3214:       x2 = - 0.5*d1/(*d2);
                   3215:    }
                   3216: #ifdef DEBUGPRAX
                   3217:     printf("   AT d1=%14.8e d2=%14.8e small=%14.8e dz=%d x1=%14.8e x2=%14.8e\n",d1,*d2,small_windows,dz,*x1,x2);
                   3218: #endif
                   3219:     if (fabs(x2) > h)
                   3220:       x2 = (x2 > 0 ? h : -h);
                   3221: L1:  /* L1 or try loop */
                   3222: #ifdef DEBUGPRAX
                   3223:     printf("   AT predicted minimum flin x2=%14.8e x1=%14.8e K=%14d NITS=%14d dirj=%d\n",x2,*x1,k,nits,j);
                   3224: #endif
                   3225:    f2 = flin(x2, j); /* x[i]+x2*v[i][j] */
                   3226: #ifdef DEBUGPRAX
                   3227:    printf("   after flin f0=%14.8e f1=%14.8e f2=%14.8e fm=%14.8e\n",f0,f1,f2, fm);
                   3228: #endif
                   3229:    if ((k < nits) && (f2 > f0)) {
                   3230: #ifdef DEBUGPRAX
                   3231:      printf("  NO SUCCESS SO TRY AGAIN;\n");
                   3232: #endif
                   3233:      k++;
                   3234:      if ((f0 < f1) && (*x1*x2 > 0.0))
                   3235:        goto L0; /* or next */
                   3236:      x2 *= 0.5;
                   3237:      goto L1;
                   3238:    }
                   3239:    nl++;
                   3240: #ifdef DEBUGPRAX
                   3241:    printf(" bebeBE end of min x1=%14.8e x2=%14.8e f1=%14.8e f2=%14.8e f0=%14.8e fm=%14.8e d2=%14.8e\n",*x1, x2, f1, f2, f0, fm, *d2);
                   3242: #endif
                   3243:    if (f2 > fm) x2 = xm; else fm = f2;
                   3244:    if (fabs(x2*(x2-*x1)) > small_windows) {
                   3245:       *d2 = (x2*(f1-f0) - *x1*(fm-f0))/(*x1*x2*(*x1-x2));
                   3246:    }
                   3247:    else {
                   3248:       if (k > 0) *d2 = 0;
                   3249:    }
                   3250: #ifdef DEBUGPRAX
1.362     brouard  3251:    printf(" bebe end of min x1 might be very wrong x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
1.359     brouard  3252: #endif
                   3253:    if (*d2 <= small_windows) *d2 = small_windows;
                   3254:    *x1 = x2; fx = fm;
                   3255:    if (sf1 < fx) {
                   3256:       fx = sf1;
                   3257:       *x1 = sx1;
                   3258:    }
                   3259:   /*
                   3260:     Update X for linear search.
                   3261:   */
                   3262: #ifdef DEBUGPRAX
                   3263:    printf("  end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3264: #endif
                   3265:    
                   3266:    /* if (j != -1) */
                   3267:    /*    for (i=0; i<n; i++) */
                   3268:    /*        x[i] += (*x1)*v[i][j]; */
                   3269:    if (j > 0)
                   3270:       for (i=1; i<=n; i++)
                   3271:           x[i] += (*x1)*v[i][j];
                   3272: }
                   3273: 
                   3274: void quad()    /* look for a minimum along the curve q0, q1, q2        */
                   3275: {
                   3276:    int i;
                   3277:    double l, s;
                   3278: 
                   3279:    s = fx; fx = qf1; qf1 = s; qd1 = 0.0;
                   3280:    /* for (i=0; i<n; i++) { */
                   3281:    for (i=1; i<=n; i++) {
                   3282:        s = x[i]; l = q1[i]; x[i] = l; q1[i] = s;
                   3283:        qd1 = qd1 + (s-l)*(s-l);
                   3284:    }
                   3285:    s = 0.0; qd1 = sqrt(qd1); l = qd1;
                   3286: #ifdef DEBUGPRAX
                   3287:   printf("  QUAD after sqrt qd1=%14.8e \n",qd1);
                   3288: #endif
                   3289:  
                   3290:    if (qd0>0.0 && qd1>0.0 &&nl>=3*n*n) {
                   3291: #ifdef DEBUGPRAX
                   3292:      printf(" QUAD before min value=%14.8e \n",qf1);
                   3293: #endif
                   3294:       /* min(-1, 2, &s, &l, qf1, 1); */
                   3295:       minny(0, 2, &s, &l, qf1, 1);
                   3296:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3297:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3298:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3299:    }
                   3300:    else {
                   3301:       fx = qf1; qa = qb = 0.0; qc = 1.0;
                   3302:    }
                   3303: #ifdef DEBUGPRAX
                   3304:   printf("after eventual min qd0=%14.8e qd1=%14.8e nl=%d\n",qd0, qd1,nl);
                   3305: #endif
                   3306:    qd0 = qd1;
                   3307:    /* for (i=0; i<n; i++) { */
                   3308:    for (i=1; i<=n; i++) {
                   3309:        s = q0[i]; q0[i] = x[i];
                   3310:        x[i] = qa*s + qb*x[i] + qc*q1[i];
                   3311:    }
                   3312: #ifdef DEBUGQUAD
                   3313:    vecprint ( " X after QUAD:" , x, n );
                   3314: #endif
                   3315: }
                   3316: 
                   3317: /* void minfit(int n, double eps, double tol, double ab[N][N], double q[]) */
                   3318: void minfit(int n, double eps, double tol, double **ab, double q[])
                   3319: /* int n; */
                   3320: /* double eps, tol, ab[N][N], q[N]; */
                   3321: {
                   3322:    int l, kt, l2, i, j, k;
                   3323:    double c, f, g, h, s, x, y, z;
                   3324:    /* double eps; */
                   3325: /* #ifndef MSDOS */
                   3326: /*    double e[N];             /\* plenty of stack on a vax *\/ */
                   3327: /* #endif */
                   3328:    /* double *e; */
                   3329:    /* e=vector(0,n-1); /\* should be freed somewhere but gotos *\/ */
                   3330:    
                   3331:    /* householder's reduction to bidiagonal form */
                   3332: 
                   3333:    if(n==1){
                   3334:      /* q[1-1]=ab[1-1][1-1]; */
                   3335:      /* ab[1-1][1-1]=1.0; */
                   3336:      q[1]=ab[1][1];
                   3337:      ab[1][1]=1.0;
                   3338:      return; /* added from hardt */
                   3339:    }
                   3340:    /* eps=macheps; */ /* added */
                   3341:    x = g = 0.0;
                   3342: #ifdef DEBUGPRAX
                   3343:    matprint (" HOUSE holder:", ab, n, n);
                   3344: #endif
                   3345: 
                   3346:    /* for (i=0; i<n; i++) {  /\* FOR I := 1 UNTIL N DO *\/ */
                   3347:    for (i=1; i<=n; i++) {  /* FOR I := 1 UNTIL N DO */
                   3348:      e[i] = g; s = 0.0; l = i+1;
                   3349:      /* for (j=i; j<n; j++)  /\* FOR J := I UNTIL N DO S := S*AB(J,I)**2; *\/ /\* not correct *\/ */
                   3350:      for (j=i; j<=n; j++)  /* FOR J := I UNTIL N DO S := S*AB(J,I)**2; */ /* not correct */
                   3351:        s += ab[j][i] * ab[j][i];
                   3352: #ifdef DEBUGPRAXFIN
                   3353:      printf("i=%d s=%d %.7g tol=%.7g",i,s,tol);
                   3354: #endif
                   3355:      if (s < tol) {
                   3356:        g = 0.0;
                   3357:      }
                   3358:      else {
                   3359:        /* f = ab[i][i]; */
                   3360:        f = ab[i][i];
                   3361:        if (f < 0.0) 
                   3362:         g = sqrt(s);
                   3363:        else
                   3364:         g = -sqrt(s);
                   3365:        /* h = f*g - s; ab[i][i] = f - g; */
                   3366:        h = f*g - s; ab[i][i] = f - g;
                   3367:        /* for (j=l; j<n; j++) { */ /* FOR J := L UNTIL N DO */ /* wrong */
                   3368:        for (j=l; j<=n; j++) {
                   3369:         f = 0.0;
                   3370:         /* for (k=i; k<n; k++) /\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3371:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3372:           /* f += ab[k][i] * ab[k][j]; */
                   3373:           f += ab[k][i] * ab[k][j];
                   3374:         f /= h;
                   3375:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3376:           /* for (k=i; k<n; k++)/\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3377:           ab[k][j] += f * ab[k][i];
                   3378:         /* ab[k][j] += f * ab[k][i]; */
                   3379: #ifdef DEBUGPRAX
                   3380:         printf("Holder J=%d F=%.7g",j,f);
                   3381: #endif
                   3382:        }
                   3383:      } /* end s */
                   3384:      /* q[i] = g; s = 0.0; */
                   3385:      q[i] = g; s = 0.0;
                   3386: #ifdef DEBUGPRAX
                   3387:      printf(" I Q=%d %.7g",i,q[i]);
                   3388: #endif   
                   3389:        
                   3390:      /* if (i < n) */
                   3391:      /* if (i <= n)  /\* I is always lower or equal to n wasn't in golub reinsch*\/ */
                   3392:      /* for (j=l; j<n; j++) */
                   3393:      for (j=l; j<=n; j++)
                   3394:        s += ab[i][j] * ab[i][j];
                   3395:      /* s += ab[i][j] * ab[i][j]; */
                   3396:      if (s < tol) {
                   3397:        g = 0.0;
                   3398:      }
                   3399:      else {
                   3400:        if(i<n)
                   3401:         /* f = ab[i][i+1]; */ /* Brent golub overflow */
                   3402:         f = ab[i][i+1];
                   3403:        if (f < 0.0)
                   3404:         g = sqrt(s);
                   3405:        else 
                   3406:         g = - sqrt(s);
                   3407:        h = f*g - s;
                   3408:        /* h = f*g - s; ab[i][i+1] = f - g; */ /* Overflow for i=n Error in Golub too but not Burkardt*/
                   3409:        /* for (j=l; j<n; j++) */
                   3410:        /*     e[j] = ab[i][j]/h; */
                   3411:        if(i<n){
                   3412:         ab[i][i+1] = f - g;
                   3413:         for (j=l; j<=n; j++)
                   3414:           e[j] = ab[i][j]/h;
                   3415:         /* for (j=l; j<n; j++) { */
                   3416:         for (j=l; j<=n; j++) {
                   3417:           s = 0.0;
                   3418:           /* for (k=l; k<n; k++) s += ab[j][k]*ab[i][k]; */
                   3419:           for (k=l; k<=n; k++) s += ab[j][k]*ab[i][k];
                   3420:           /* for (k=l; k<n; k++) ab[j][k] += s * e[k]; */
                   3421:           for (k=l; k<=n; k++) ab[j][k] += s * e[k];
                   3422:         } /* END J */
                   3423:        } /* END i <n */
                   3424:      } /* end s */
                   3425:        /* y = fabs(q[i]) + fabs(e[i]); */
                   3426:      y = fabs(q[i]) + fabs(e[i]);
                   3427:      if (y > x) x = y;
                   3428: #ifdef DEBUGPRAX
                   3429:      printf(" I Y=%d %.7g",i,y);
                   3430: #endif
                   3431: #ifdef DEBUGPRAX
                   3432:      printf(" i=%d e(i) %.7g",i,e[i]);
                   3433: #endif
                   3434:    } /* end i */
                   3435:    /*
                   3436:      Accumulation of right hand transformations */
                   3437:    /* for (i=n-1; i >= 0; i--) { */ /* FOR I := N STEP -1 UNTIL 1 DO */
                   3438:    /* We should avoid the overflow in Golub */
                   3439:    /* ab[n-1][n-1] = 1.0; */
                   3440:    /* g = e[n-1]; */
                   3441:    ab[n][n] = 1.0;
                   3442:    g = e[n];
                   3443:    l = n;
                   3444: 
                   3445:    /* for (i=n; i >= 1; i--) { */
                   3446:    for (i=n-1; i >= 1; i--) { /* n-1 loops, different from brent and golub*/
                   3447:      if (g != 0.0) {
                   3448:        /* h = ab[i-1][i]*g; */
                   3449:        h = ab[i][i+1]*g;
                   3450:        for (j=l; j<=n; j++) ab[j][i] = ab[i][j] / h;
                   3451:        for (j=l; j<=n; j++) {
                   3452:         /* h = ab[i][i+1]*g; */
                   3453:         /* for (j=l; j<n; j++) ab[j][i] = ab[i][j] / h; */
                   3454:         /* for (j=l; j<n; j++) { */
                   3455:         s = 0.0;
                   3456:         /* for (k=l; k<n; k++) s += ab[i][k] * ab[k][j]; */
                   3457:         /* for (k=l; k<n; k++) ab[k][j] += s * ab[k][i]; */
                   3458:         for (k=l; k<=n; k++) s += ab[i][k] * ab[k][j];
                   3459:         for (k=l; k<=n; k++) ab[k][j] += s * ab[k][i];
                   3460:        }/* END J */
                   3461:      }/* END G */
                   3462:      /* for (j=l; j<n; j++) */
                   3463:      /*     ab[i][j] = ab[j][i] = 0.0; */
                   3464:      /* ab[i][i] = 1.0; g = e[i]; l = i; */
                   3465:      for (j=l; j<=n; j++)
                   3466:        ab[i][j] = ab[j][i] = 0.0;
                   3467:      ab[i][i] = 1.0; g = e[i]; l = i;
                   3468:    }/* END I */
                   3469: #ifdef DEBUGPRAX
                   3470:    matprint (" HOUSE accumulation:",ab,n, n );
                   3471: #endif
                   3472: 
                   3473:    /* diagonalization to bidiagonal form */
                   3474:    eps *= x;
                   3475:    /* for (k=n-1; k>= 0; k--) { */
                   3476:    for (k=n; k>= 1; k--) {
                   3477:      kt = 0;
                   3478: TestFsplitting:
                   3479: #ifdef DEBUGPRAX
                   3480:      printf(" TestFsplitting: k=%d kt=%d\n",k,kt);
                   3481:      /* for(i=1;i<=n;i++)printf(" e(%d)=%.14f",i,e[i]);printf("\n"); */
                   3482: #endif     
                   3483:      kt = kt+1; 
                   3484: /* TestFsplitting: */
                   3485:      /* if (++kt > 30) { */
                   3486:      if (kt > 30) { 
                   3487:        e[k] = 0.0;
                   3488:        fprintf(stderr, "\n+++ MINFIT - Fatal error\n");
                   3489:        fprintf ( stderr, "  The QR algorithm failed to converge.\n" );
                   3490:      }
                   3491:      /* for (l2=k; l2>=0; l2--) { */
                   3492:      for (l2=k; l2>=1; l2--) {
                   3493:        l = l2;
                   3494: #ifdef DEBUGPRAX
                   3495:        printf(" l e(l)< eps %d %.7g %.7g ",l,e[l], eps);
                   3496: #endif
                   3497:        /* if (fabs(e[l]) <= eps) */
                   3498:        if (fabs(e[l]) <= eps)
                   3499:         goto TestFconvergence;
                   3500:        /* if (fabs(q[l-1]) <= eps)*/ /* missing if ( 1 < l ){ *//* printf(" q(l-1)< eps %d %.7g %.7g ",l-1,q[l-2], eps); */
                   3501:        if (fabs(q[l-1]) <= eps)
                   3502:         break; /* goto Cancellation; */
                   3503:      }
                   3504:    Cancellation:
                   3505: #ifdef DEBUGPRAX
                   3506:      printf(" Cancellation:\n");
                   3507: #endif     
                   3508:      c = 0.0; s = 1.0;
                   3509:      for (i=l; i<=k; i++) {
                   3510:        f = s * e[i]; e[i] *= c;
                   3511:        /* f = s * e[i]; e[i] *= c; */
                   3512:        if (fabs(f) <= eps)
                   3513:         goto TestFconvergence;
                   3514:        /* g = q[i]; */
                   3515:        g = q[i];
                   3516:        if (fabs(f) < fabs(g)) {
                   3517:         double fg = f/g;
                   3518:         h = fabs(g)*sqrt(1.0+fg*fg);
                   3519:        }
                   3520:        else {
                   3521:         double gf = g/f;
                   3522:         h = (f!=0.0 ? fabs(f)*sqrt(1.0+gf*gf) : 0.0);
                   3523:        }
                   3524:        /*    COMMENT: THE ABOVE REPLACES Q(I):=H:=LONGSQRT(G*G+F*F) */
                   3525:        /* WHICH MAY GIVE INCORRECT RESULTS IF THE */
                   3526:        /* SQUARES UNDERFLOW OR IF F = G = 0; */
                   3527:        
                   3528:        /* q[i] = h; */
                   3529:        q[i] = h;
                   3530:        if (h == 0.0) { h = 1.0; g = 1.0; }
                   3531:        c = g/h; s = -f/h;
                   3532:      }
                   3533: TestFconvergence:
                   3534:  #ifdef DEBUGPRAX
                   3535:      printf(" TestFconvergence: l=%d k=%d\n",l,k);
                   3536: #endif     
                   3537:      /* z = q[k]; */
                   3538:      z = q[k];
                   3539:      if (l == k)
                   3540:        goto Convergence;
                   3541:      /* shift from bottom 2x2 minor */
                   3542:      /* x = q[l]; y = q[k-l]; g = e[k-1]; h = e[k]; */ /* Error */
                   3543:      x = q[l]; y = q[k-1]; g = e[k-1]; h = e[k];
                   3544:      f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2.0*h*y);
                   3545:      g = sqrt(f*f+1.0);
                   3546:      if (f <= 0.0)
                   3547:        f = ((x-z)*(x+z) + h*(y/(f-g)-h))/x;
                   3548:      else
                   3549:        f = ((x-z)*(x+z) + h*(y/(f+g)-h))/x;
                   3550:      /* next qr transformation */
                   3551:      s = c = 1.0;
                   3552:      for (i=l+1; i<=k; i++) {
                   3553: #ifdef DEBUGPRAXQR
                   3554:        printf(" Before Mid TestFconvergence: l+1=%d i=%d k=%d h=%.6e e(i)=%14.8f e(i-1)=%14.8f\n",l+1,i,k, h, e[i],e[i-1]);
                   3555: #endif     
                   3556:        /* g = e[i]; y = q[i]; h = s*g; g *= c; */
                   3557:        g = e[i]; y = q[i]; h = s*g; g *= c;
                   3558:        if (fabs(f) < fabs(h)) {
                   3559:         double fh = f/h;
                   3560:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3561:        }
                   3562:        else {
                   3563:         double hf = h/f;
                   3564:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3565:        }
                   3566:        /* e[i-1] = z; */
                   3567:        e[i-1] = z;
                   3568: #ifdef DEBUGPRAXQR
                   3569:        printf(" Mid TestFconvergence: l+1=%d i=%d k=%d h=%.6e e(i)=%14.8f e(i-1)=%14.8f\n",l+1,i,k, h, e[i],e[i-1]);
                   3570: #endif     
                   3571:        if (z == 0.0) 
                   3572:         f = z = 1.0;
                   3573:        c = f/z; s = h/z;
                   3574:        f = x*c + g*s; g = - x*s + g*c; h = y*s;
                   3575:        y *= c;
                   3576:        /* for (j=0; j<n; j++) { */
                   3577:        /*     x = ab[j][i-1]; z = ab[j][i]; */
                   3578:        /*     ab[j][i-1] = x*c + z*s; */
                   3579:        /*     ab[j][i] = - x*s + z*c; */
                   3580:        /* } */
                   3581:        for (j=1; j<=n; j++) {
                   3582:         x = ab[j][i-1]; z = ab[j][i];
                   3583:         ab[j][i-1] = x*c + z*s;
                   3584:         ab[j][i] = - x*s + z*c;
                   3585:        }
                   3586:        if (fabs(f) < fabs(h)) {
                   3587:         double fh = f/h;
                   3588:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3589:        }
                   3590:        else {
                   3591:         double hf = h/f;
                   3592:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3593:        }
                   3594: #ifdef DEBUGPRAXQR
                   3595:        printf(" qr transformation z f h=%.7g %.7g %.7g i=%d k=%d\n",z,f,h, i, k);
                   3596: #endif
                   3597:        q[i-1] = z;
                   3598:        if (z == 0.0)
                   3599:         z = f = 1.0;
                   3600:        c = f/z; s = h/z;
                   3601:        f = c*g + s*y;  /* f can be very small */
                   3602:        x = - s*g + c*y;
                   3603:      }
                   3604:      /* e[l] = 0.0; e[k] = f; q[k] = x; */
                   3605:      e[l] = 0.0; e[k] = f; q[k] = x;
                   3606: #ifdef DEBUGPRAXQR
                   3607:      printf(" aftermid loop l=%d k=%d e(l)=%7g e(k)=%.7g q(k)=%.7g x=%.7g\n",l,k,e[l],e[k],q[k],x);
                   3608: #endif
                   3609:      goto TestFsplitting;
                   3610:    Convergence:
                   3611: #ifdef DEBUGPRAX
                   3612:      printf(" Convergence:\n");
                   3613: #endif     
                   3614:      if (z < 0.0) {
                   3615:        /* q[k] = - z; */
                   3616:        /* for (j=0; j<n; j++) ab[j][k] = - ab[j][k]; */
                   3617:        q[k] = - z;
                   3618:        for (j=1; j<=n; j++) ab[j][k] = - ab[j][k];
                   3619:      }/* END Z */
                   3620:    }/* END K */
                   3621: } /* END MINFIT */
                   3622: 
                   3623: 
                   3624: double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x))
                   3625: /* double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x, int _n)) */
                   3626: /* double praxis(double (*_fun)(), double _x[], int _n) */
                   3627: /* double (*_fun)(); */
                   3628: /* double _x[N]; */
                   3629: /* double (*_fun)(); */
                   3630: /* double _x[N]; */
                   3631: {
                   3632:    /* init global extern variables and parameters */
                   3633:    /* double *d, *y, *z, */
                   3634:    /*   *q0, *q1, **v; */
                   3635:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   3636:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   3637: 
                   3638:   
                   3639:   int seed; /* added */
                   3640:   int biter=0;
                   3641:   double r;
                   3642:   double randbrent( int (*));
                   3643:   double s, sf;
                   3644:   
                   3645:    h = h0; /* step; */
                   3646:    t = tol;
                   3647:    scbd = 1.0;
                   3648:    illc = 0;
                   3649:    ktm = 1;
                   3650: 
                   3651:    macheps = DBL_EPSILON;
                   3652:    /* prin=4; */
                   3653: #ifdef DEBUGPRAX
                   3654:    printf("Praxis macheps=%14g h=%14g step=%14g tol=%14g\n",macheps,h, h0,tol); 
                   3655: #endif
                   3656:    n = _n;
                   3657:    x = _x;
                   3658:    prin = _prin;
                   3659:    fun = _fun;
                   3660:    d=vector(1, n);
                   3661:    y=vector(1, n);
                   3662:    z=vector(1, n);
                   3663:    q0=vector(1, n);
                   3664:    q1=vector(1, n);
                   3665:    e=vector(1, n);
                   3666:    tflin=vector(1, n);
                   3667:    v=matrix(1, n, 1, n);
                   3668:    for(i=1;i<=n;i++){d[i]=y[i]=z[i]=q0[0]=e[i]=tflin[i]=0.;}
                   3669:    small_windows = (macheps) * (macheps); vsmall = small_windows*small_windows;
                   3670:    large = 1.0/small_windows; vlarge = 1.0/vsmall;
                   3671:    m2 = sqrt(macheps); m4 = sqrt(m2);
                   3672:    seed = 123456789; /* added */
                   3673:    ldfac = (illc ? 0.1 : 0.01);
                   3674:    for(i=1;i<=n;i++) z[i]=0.; /* Was missing in Gegenfurtner as well as Brent's algol or fortran  */
                   3675:    nl = kt = 0; nf = 1;
                   3676: #ifdef NR_SHIFT
                   3677:    fx = (*fun)((x-1), n);
                   3678: #else
                   3679:    fx = (*fun)(x);
                   3680: #endif
                   3681:    qf1 = fx;
                   3682:    t2 = small_windows + fabs(t); t = t2; dmin = small_windows;
                   3683: #ifdef DEBUGPRAX
                   3684:    printf("praxis2 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3685: #endif
                   3686:    if (h < 100.0*t) h = 100.0*t;
                   3687: #ifdef DEBUGPRAX
                   3688:    printf("praxis3 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3689: #endif
                   3690:    ldt = h;
                   3691:    /* for (i=0; i<n; i++) for (j=0; j<n; j++) */
                   3692:    for (i=1; i<=n; i++) for (j=1; j<=n; j++)
                   3693:        v[i][j] = (i == j ? 1.0 : 0.0);
                   3694:    d[1] = 0.0; qd0 = 0.0;
                   3695:    /* for (i=0; i<n; i++) q1[i] = x[i]; */
                   3696:    for (i=1; i<=n; i++) q1[i] = x[i];
                   3697:    if (prin > 1) {
                   3698:       printf("\n------------- enter function praxis -----------\n");
                   3699:       printf("... current parameter settings ...\n");
                   3700:       printf("... scaling ... %20.10e\n", scbd);
                   3701:       printf("...   tol   ... %20.10e\n", t);
                   3702:       printf("... maxstep ... %20.10e\n", h);
                   3703:       printf("...   illc  ... %20u\n", illc);
                   3704:       printf("...   ktm   ... %20u\n", ktm);
                   3705:       printf("... maxfun  ... %20u\n", maxfun);
                   3706:    }
                   3707:    if (prin) print2();
                   3708: 
                   3709: mloop:
                   3710:     biter++;  /* Added to count the loops */
                   3711:    /* sf = d[0]; */
                   3712:    /* s = d[0] = 0.0; */
                   3713:     printf("\n Big iteration %d \n",biter);
                   3714:     fprintf(ficlog,"\n Big iteration %d \n",biter);
                   3715:     sf = d[1];
                   3716:    s = d[1] = 0.0;
                   3717: 
                   3718:    /* minimize along first direction V(*,1) */
                   3719: #ifdef DEBUGPRAX
                   3720:    printf("  Minimize along the first direction V(*,1). illc=%d\n",illc);
                   3721:    /* fprintf(ficlog,"  Minimize along the first direction V(*,1).\n"); */
                   3722: #endif
                   3723: #ifdef DEBUGPRAX2
                   3724:    printf("praxis4 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3725: #endif
                   3726:    /* min(0, 2, &d[0], &s, fx, 0); /\* mac heps not global *\/ */
1.362     brouard  3727:    minny(1, 2, &d[1], &s, fx, 0); /* mac heps not global it seems that fx doesn't correspond to f(s=*x1) */
1.359     brouard  3728: #ifdef DEBUGPRAX
                   3729:    printf("praxis5 macheps=%14g h=%14g looks at sign of s=%14g fx=%14g\n",macheps,h, s,fx); 
                   3730: #endif
                   3731:    if (s <= 0.0)
                   3732:       /* for (i=0; i < n; i++) */
                   3733:       for (i=1; i <= n; i++)
                   3734:           v[i][1] = -v[i][1];
                   3735:    /* if ((sf <= (0.9 * d[0])) || ((0.9 * sf) >= d[0])) */
                   3736:    if ((sf <= (0.9 * d[1])) || ((0.9 * sf) >= d[1]))
                   3737:       /* for (i=1; i<n; i++) */
                   3738:       for (i=2; i<=n; i++)
                   3739:           d[i] = 0.0;
                   3740:    /* for (k=1; k<n; k++) { */
                   3741:    for (k=2; k<=n; k++) {
                   3742:     /*
                   3743:       The inner loop starts here.
                   3744:     */
                   3745: #ifdef DEBUGPRAX
                   3746:       printf("      The inner loop  here from k=%d to n=%d.\n",k,n);
                   3747:       /* fprintf(ficlog,"      The inner loop  here from k=%d to n=%d.\n",k,n); */
                   3748: #endif
                   3749:        /* for (i=0; i<n; i++) */
                   3750:        for (i=1; i<=n; i++)
                   3751:            y[i] = x[i];
                   3752:        sf = fx;
                   3753: #ifdef DEBUGPRAX
                   3754:        printf(" illc=%d and kt=%d and ktm=%d\n", illc, kt, ktm);
                   3755: #endif
                   3756:        illc = illc || (kt > 0);
                   3757: next:
                   3758:        kl = k;
                   3759:        df = 0.0;
                   3760:        if (illc) {        /* random step to get off resolution valley */
                   3761: #ifdef DEBUGPRAX
                   3762:          printf("  A random step follows, to avoid resolution valleys.\n");
                   3763:          matprint("  before rand, vectors:",v,n,n);
                   3764: #endif
                   3765:           for (i=1; i<=n; i++) {
                   3766: #ifdef NOBRENTRAND
                   3767:            r = drandom();
                   3768: #else
                   3769:            seed=i;
                   3770:            /* seed=i+1; */
                   3771: #ifdef DEBUGRAND
                   3772:            printf(" Random seed=%d, brent i=%d",seed,i); /* YYYY i=5 j=1 vji= -0.0001170073 */
                   3773: #endif
                   3774:            r = randbrent ( &seed );
                   3775: #endif
                   3776: #ifdef DEBUGRAND
                   3777:            printf(" Random r=%.7g \n",r);
                   3778: #endif     
                   3779:             z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (r - 0.5);
                   3780:            /* z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (drandom() - 0.5); */
                   3781: 
                   3782:            s = z[i];
                   3783:               for (j=1; j <= n; j++)
                   3784:                   x[j] += s * v[j][i];
                   3785:          }
                   3786: #ifdef DEBUGRAND
                   3787:          matprint("  after rand, vectors:",v,n,n);
                   3788: #endif
                   3789: #ifdef NR_SHIFT
                   3790:           fx = (*fun)((x-1), n);
                   3791: #else
                   3792:           fx = (*fun)(x, n);
                   3793: #endif
                   3794:           /* fx = (*func) ( (x-1) ); *//* This for func which is computed from x[1] and not from x[0] xm1=(x-1)*/
                   3795:           nf++;
                   3796:        }
                   3797:        /* minimize along non-conjugate directions */
                   3798: #ifdef DEBUGPRAX
                   3799:        printf(" Minimize along the 'non-conjugate' directions (dots printed) V(*,%d),...,V(*,%d).\n",k,n);
                   3800:        /* fprintf(ficlog," Minimize along the 'non-conjugate' directions  (dots printed) V(*,%d),...,V(*,%d).\n",k,n); */
                   3801: #endif
                   3802:        /* for (k2=k; k2<n; k2++) {  /\* Be careful here k2 <=n ? *\/ */
                   3803:        for (k2=k; k2<=n; k2++) {  /* Be careful here k2 <=n ? */
                   3804:            sl = fx;
                   3805:            s = 0.0;
                   3806: #ifdef DEBUGPRAX
                   3807:           printf(" Minimize along the 'NON-CONJUGATE' true direction k2=%14d fx=%14.7f\n",k2, fx);
                   3808:    matprint("  before min vectors:",v,n,n);
                   3809: #endif
                   3810:            /* min(k2, 2, &d[k2], &s, fx, 0); */
                   3811:    /*    jsearch=k2-1; */
                   3812:    /* min(jsearch, 2, &d[jsearch], &s, fx, 0); */
                   3813:    minny(k2, 2, &d[k2], &s, fx, 0);
                   3814: #ifdef DEBUGPRAX
                   3815:           printf(" . D(%d)=%14.7f d[k2]=%14.7f z[k2]=%14.7f illc=%14d fx=%14.7f\n",k2,d[k2],d[k2],z[k2],illc,fx);
                   3816: #endif
                   3817:           if (illc) {
                   3818:              /* double szk = s + z[k2]; */
                   3819:               /* s = d[k2] * szk*szk; */
                   3820:              double szk = s + z[k2];
                   3821:               s = d[k2] * szk*szk;
                   3822:           }
                   3823:            else 
                   3824:              s = sl - fx;
                   3825:            /* if (df < s) { */
                   3826:            if (df <= s) {
                   3827:               df = s;
                   3828:               kl = k2;
                   3829: #ifdef DEBUGPRAX
                   3830:            printf(" df=%.7g and choose kl=%d \n",df,kl); /* UUUU */
                   3831: #endif
                   3832:            }
                   3833:        } /* end loop k2 */
                   3834:         /*
                   3835:          If there was not much improvement on the first try, set
                   3836:          ILLC = true and start the inner loop again.
                   3837:        */
                   3838: #ifdef DEBUGPRAX
                   3839:        printf(" If there was not much improvement on the first try, set ILLC = true and start the inner loop again. illc=%d\n",illc);
                   3840:        /* fprintf(ficlog,"  If there was not much improvement on the first try, set ILLC = true and start the inner loop again.\n"); */
                   3841: #endif
                   3842:         if (!illc && (df < fabs(100.0 * (macheps) * fx))) {
                   3843: #ifdef DEBUGPRAX
                   3844:          printf("\n NO SUCCESS because DF is small, starts inner loop with same K(=%d), fabs(  100.0 * machep(=%.10e) * fx(=%.9e) )=%.9e > df(=%.9e) break illc=%d\n", k, macheps, fx, fabs ( 100.0 * macheps * fx ), df, illc);         
                   3845: #endif
                   3846:           illc = 1;
                   3847:           goto next;
                   3848:        }
                   3849: #ifdef DEBUGPRAX
                   3850:        printf("\n SUCCESS, BREAKS inner loop K(=%d) because DF is big, fabs(  100.0 * machep(=%.10e) * fx(=%.9e) )=%.9e <= df(=%.9e) break illc=%d\n", k, macheps, fx, fabs ( 100.0 * macheps * fx ), df, illc);
                   3851: #endif
                   3852:        
                   3853:        /* if ((k == 1) && (prin > 1)){ /\* be careful k=2 *\/ */
                   3854:        if ((k == 2) && (prin > 1)){ /* be careful k=2 */
                   3855: #ifdef DEBUGPRAX
                   3856:         printf("  NEW D The second difference array d:\n" );
                   3857:         /* fprintf(ficlog, " NEW D The second difference array d:\n" ); */
                   3858: #endif
                   3859:         vecprint(" NEW D The second difference array d:",d,n);
                   3860:        }
                   3861:        /* minimize along conjugate directions */ 
                   3862:        /*
                   3863:         Minimize along the "conjugate" directions V(*,1),...,V(*,K-1).
                   3864:        */
                   3865: #ifdef DEBUGPRAX
                   3866:       printf("Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1);
                   3867:       /* fprintf(ficlog,"Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1); */
                   3868: #endif
                   3869:       /* for (k2=0; k2<=k-1; k2++) { */
                   3870:       for (k2=1; k2<=k-1; k2++) {
                   3871:            s = 0.0;
                   3872:            /* min(k2-1, 2, &d[k2-1], &s, fx, 0); */
                   3873:            minny(k2, 2, &d[k2], &s, fx, 0);
                   3874:        }
                   3875:        f1 = fx;
                   3876:        fx = sf;
                   3877:        lds = 0.0;
                   3878:        /* for (i=0; i<n; i++) { */
                   3879:        for (i=1; i<=n; i++) {
                   3880:            sl = x[i];
                   3881:            x[i] = y[i];
                   3882:            y[i] = sl - y[i];
                   3883:            sl = y[i];
                   3884:            lds = lds + sl*sl;
                   3885:        }
                   3886:        lds = sqrt(lds);
                   3887: #ifdef DEBUGPRAX
                   3888:        printf("Minimization done 'conjugate', shifted all points, computed lds=%.8f\n",lds);
                   3889: #endif      
                   3890:       /*
                   3891:        Discard direction V(*,kl).
                   3892:        
                   3893:        If no random step was taken, V(*,KL) is the "non-conjugate"
                   3894:        direction along which the greatest improvement was made.
                   3895:       */
                   3896:        if (lds > small_windows) {
                   3897: #ifdef DEBUGPRAX
                   3898:        printf("lds big enough to throw direction  V(*,kl=%d). If no random step was taken, V(*,KL) is the 'non-conjugate' direction along which the greatest improvement was made.\n",kl);
                   3899:         matprint("  before shift new conjugate vectors:",v,n,n);
                   3900: #endif
                   3901:         for (i=kl-1; i>=k; i--) {
                   3902:           /* for (j=0; j < n; j++) */
                   3903:           for (j=1; j <= n; j++)
                   3904:             /* v[j][i+1] = v[j][i]; */ /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3905:             v[j][i+1] = v[j][i]; /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3906:           /* v[j][i+1] = v[j][i]; */
                   3907:           /* d[i+1] = d[i];*/  /* last  is d[k+1]= d[k] */
                   3908:           d[i+1] = d[i];  /* last  is d[k]= d[k-1] */
                   3909:         }
                   3910: #ifdef DEBUGPRAX
                   3911:         matprint("  after shift new conjugate vectors:",v,n,n);         
                   3912: #endif  /* d[k] = 0.0; */
                   3913:         d[k] = 0.0;
                   3914:         for (i=1; i <= n; i++)
                   3915:           v[i][k] = y[i] / lds;
                   3916:         /* v[i][k] = y[i] / lds; */
                   3917: #ifdef DEBUGPRAX
                   3918:         printf("Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x). d2=%14.7g lds=%.10f\n",k,d[k],lds);
                   3919:         /* fprintf(ficlog,"Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x).\n",k); */
                   3920:     matprint("  before min new conjugate vectors:",v,n,n);      
                   3921: #endif
                   3922:         /* min(k-1, 4, &d[k-1], &lds, f1, 1); */
                   3923:         minny(k, 4, &d[k], &lds, f1, 1);
                   3924: #ifdef DEBUGPRAX
                   3925:         printf(" after min d(k)=%d %.7g lds=%14f\n",k,d[k],lds);
                   3926:    matprint("  after min vectors:",v,n,n);
                   3927: #endif
                   3928:         if (lds <= 0.0) {
                   3929:           lds = -lds;
                   3930: #ifdef DEBUGPRAX
                   3931:          printf(" lds changed sign lds=%.14f k=%d\n",lds,k);
                   3932: #endif    
                   3933:           /* for (i=0; i<n; i++) */
                   3934:           /*   v[i][k] = -v[i][k]; */
                   3935:           for (i=1; i<=n; i++)
                   3936:             v[i][k] = -v[i][k];
                   3937:         }
                   3938:        }
                   3939:        ldt = ldfac * ldt;
                   3940:        if (ldt < lds)
                   3941:           ldt = lds;
                   3942:        if (prin > 0){
                   3943: #ifdef DEBUGPRAX
                   3944:        printf(" k=%d",k);
                   3945:        /* fprintf(ficlog," k=%d",k); */
                   3946: #endif
                   3947:        print2();/* n, x, prin, fx, nf, nl ); */
                   3948:        }
                   3949:        t2 = 0.0;
                   3950:        /* for (i=0; i<n; i++) */
                   3951:        for (i=1; i<=n; i++)
                   3952:            t2 += x[i]*x[i];
                   3953:        t2 = m2 * sqrt(t2) + t;
                   3954:        /*
                   3955:        See whether the length of the step taken since starting the
                   3956:        inner loop exceeds half the tolerance.
                   3957:       */
                   3958: #ifdef DEBUGPRAX
                   3959:        printf("See if step length exceeds half the tolerance.\n"); /* ZZZZZ */
                   3960:       /* fprintf(ficlog,"See if step length exceeds half the tolerance.\n"); */
                   3961: #endif
                   3962:        if (ldt > (0.5 * t2))
                   3963:           kt = 0;
                   3964:        else 
                   3965:          kt++;
                   3966: #ifdef DEBUGPRAX
                   3967:        printf("if kt=%d >? ktm=%d gotoL2 loop\n",kt,ktm);
                   3968: #endif
                   3969:        if (kt > ktm){
                   3970:          if ( 0 < prin ){
                   3971:           /* printf("\nr8vec_print\n X:\n"); */
                   3972:           /* fprintf(ficlog,"\nr8vec_print\n X:\n"); */
                   3973:           vecprint ("END  X:", x, n );
                   3974:         }
                   3975:            goto fret;
                   3976:        }
                   3977: #ifdef DEBUGPRAX
                   3978:    matprint("  end of L2 loop vectors:",v,n,n);
                   3979: #endif
                   3980:        
                   3981:    }
                   3982:    /* printf("The inner loop ends here.\n"); */
                   3983:    /* fprintf(ficlog,"The inner loop ends here.\n"); */
                   3984:    /*
                   3985:      The inner loop ends here.
                   3986:      
                   3987:      Try quadratic extrapolation in case we are in a curved valley.
                   3988:    */
                   3989: #ifdef DEBUGPRAX
                   3990:    printf("Try QUAD ratic extrapolation in case we are in a curved valley.\n");
                   3991: #endif
                   3992:    /*  try quadratic extrapolation in case    */
                   3993:    /*  we are stuck in a curved valley        */
                   3994:    quad();
                   3995:    dn = 0.0;
                   3996:    /* for (i=0; i<n; i++) { */
                   3997:    for (i=1; i<=n; i++) {
                   3998:        d[i] = 1.0 / sqrt(d[i]);
                   3999:        if (dn < d[i])
                   4000:           dn = d[i];
                   4001:    }
                   4002:    if (prin > 2)
                   4003:      matprint("  NEW DIRECTIONS vectors:",v,n,n);
                   4004:    /* for (j=0; j<n; j++) { */
                   4005:    for (j=1; j<=n; j++) {
                   4006:        s = d[j] / dn;
                   4007:        /* for (i=0; i < n; i++) */
                   4008:        for (i=1; i <= n; i++)
                   4009:            v[i][j] *= s;
                   4010:    }
                   4011:    
                   4012:    if (scbd > 1.0) {       /* scale axis to reduce condition number */
                   4013: #ifdef DEBUGPRAX
                   4014:      printf("Scale the axes to try to reduce the condition number.\n");
                   4015: #endif
                   4016:      /* fprintf(ficlog,"Scale the axes to try to reduce the condition number.\n"); */
                   4017:       s = vlarge;
                   4018:       /* for (i=0; i<n; i++) { */
                   4019:       for (i=1; i<=n; i++) {
                   4020:           sl = 0.0;
                   4021:           /* for (j=0; j < n; j++) */
                   4022:           for (j=1; j <= n; j++)
                   4023:               sl += v[i][j]*v[i][j];
                   4024:           z[i] = sqrt(sl);
                   4025:           if (z[i] < m4)
                   4026:              z[i] = m4;
                   4027:           if (s > z[i])
                   4028:              s = z[i];
                   4029:       }
                   4030:       /* for (i=0; i<n; i++) { */
                   4031:       for (i=1; i<=n; i++) {
                   4032:           sl = s / z[i];
                   4033:           z[i] = 1.0 / sl;
                   4034:           if (z[i] > scbd) {
                   4035:              sl = 1.0 / scbd;
                   4036:              z[i] = scbd;
                   4037:           }
                   4038:       }
                   4039:    }
                   4040:    for (i=1; i<=n; i++)
                   4041:        /* for (j=0; j<=i-1; j++) { */
                   4042:        /* for (j=1; j<=i; j++) { */
                   4043:        for (j=1; j<=i-1; j++) {
                   4044:            s = v[i][j];
                   4045:            v[i][j] = v[j][i];
                   4046:            v[j][i] = s;
                   4047:        }
                   4048: #ifdef DEBUGPRAX
                   4049:     printf(" Calculate a new set of orthogonal directions before repeating  the main loop.\n  Transpose V for MINFIT:...\n");
                   4050: #endif
                   4051:       /*
                   4052:       MINFIT finds the singular value decomposition of V.
                   4053: 
                   4054:       This gives the principal values and principal directions of the
                   4055:       approximating quadratic form without squaring the condition number.
                   4056:     */
                   4057:  #ifdef DEBUGPRAX
                   4058:     printf(" MINFIT finds the singular value decomposition of V. \n This gives the principal values and principal directions of the\n  approximating quadratic form without squaring the condition number...\n");
                   4059: #endif
                   4060: 
                   4061:    minfit(n, macheps, vsmall, v, d);
                   4062:     /* for(i=0; i<n;i++)printf(" %14.7g",d[i]); */
                   4063:     /* v is overwritten with R. */
                   4064:     /*
                   4065:       Unscale the axes.
                   4066:     */
                   4067:    if (scbd > 1.0) {
                   4068: #ifdef DEBUGPRAX
                   4069:       printf(" Unscale the axes.\n");
                   4070: #endif
                   4071:       /* for (i=0; i<n; i++) { */
                   4072:       for (i=1; i<=n; i++) {
                   4073:           s = z[i];
                   4074:           /* for (j=0; j<n; j++) */
                   4075:           for (j=1; j<=n; j++)
                   4076:               v[i][j] *= s;
                   4077:       }
                   4078:       /* for (i=0; i<n; i++) { */
                   4079:       for (i=1; i<=n; i++) {
                   4080:           s = 0.0;
                   4081:           /* for (j=0; j<n; j++) */
                   4082:           for (j=1; j<=n; j++)
                   4083:               s += v[j][i]*v[j][i];
                   4084:           s = sqrt(s);
                   4085:           d[i] *= s;
                   4086:           s = 1.0 / s;
                   4087:           /* for (j=0; j<n; j++) */
                   4088:           for (j=1; j<=n; j++)
                   4089:               v[j][i] *= s;
                   4090:       }
                   4091:    }
                   4092:    /* for (i=0; i<n; i++) { */
                   4093:    double dni; /* added for compatibility with buckhardt but not brent */
                   4094:    for (i=1; i<=n; i++) {
                   4095:      dni=dn*d[i]; /* added for compatibility with buckhardt but not brent */
                   4096:        if ((dn * d[i]) > large)
                   4097:           d[i] = vsmall;
                   4098:        else if ((dn * d[i]) < small_windows)
                   4099:           d[i] = vlarge;
                   4100:        else 
                   4101:         d[i] = 1.0 / dni / dni; /* added for compatibility with buckhardt but not brent */
                   4102:           /* d[i] = pow(dn * d[i],-2.0); */
                   4103:    }
                   4104: #ifdef DEBUGPRAX
                   4105:    vecprint ("\n Before sort Eigenvalues of a:",d,n );
                   4106: #endif
                   4107:    
                   4108:    sort();               /* the new eigenvalues and eigenvectors */
                   4109: #ifdef DEBUGPRAX
                   4110:    vecprint( " After sort the eigenvalues ....\n", d, n);
                   4111:    matprint( " After sort the eigenvectors....\n", v, n,n);
                   4112: #endif
                   4113: #ifdef DEBUGPRAX
                   4114:     printf("  Determine the smallest eigenvalue.\n");
                   4115: #endif
                   4116:    /* dmin = d[n-1]; */
                   4117:    dmin = d[n];
                   4118:    if (dmin < small_windows)
                   4119:       dmin = small_windows;
                   4120:     /*
                   4121:      The ratio of the smallest to largest eigenvalue determines whether
                   4122:      the system is ill conditioned.
                   4123:    */
                   4124:   
                   4125:    /* illc = (m2 * d[0]) > dmin; */
                   4126:    illc = (m2 * d[1]) > dmin;
                   4127: #ifdef DEBUGPRAX
                   4128:     printf("  The ratio of the smallest to largest eigenvalue determines whether\n  the system is ill conditioned=%d . dmin=%.10lf < m2=%.10lf * d[1]=%.10lf \n",illc, dmin,m2, d[1]);
                   4129: #endif
                   4130:    
                   4131:    if ((prin > 2) && (scbd > 1.0))
                   4132:       vecprint("\n The scale factors:",z,n);
                   4133:    if (prin > 2)
                   4134:       vecprint("  Principal values (EIGEN VALUES OF A) of the quadratic form:",d,n);
                   4135:    if (prin > 2)
                   4136:      matprint("  The principal axes (EIGEN VECTORS OF A:",v,n, n);
                   4137: 
                   4138:    if ((maxfun > 0) && (nf > maxfun)) {
                   4139:       if (prin)
                   4140:         printf("\n... maximum number of function calls reached ...\n");
                   4141:       goto fret;
                   4142:    }
                   4143: #ifdef DEBUGPRAX
                   4144:    printf("Goto main loop\n");
                   4145: #endif
                   4146:    goto mloop;          /* back to main loop */
                   4147: 
                   4148: fret:
                   4149:    if (prin > 0) {
                   4150:          vecprint("\n  X:", x, n);
                   4151:          /* printf("\n... ChiSq reduced to %20.10e ...\n", fx); */
                   4152:         /* printf("... after %20u function calls.\n", nf); */
                   4153:    }
                   4154:    free_vector(d, 1, n);
                   4155:    free_vector(y, 1, n);
                   4156:    free_vector(z, 1, n);
                   4157:    free_vector(q0, 1, n);
                   4158:    free_vector(q1, 1, n);
                   4159:    free_matrix(v, 1, n, 1, n);
                   4160:    /*   double *d, *y, *z, */
                   4161:    /* *q0, *q1, **v; */
                   4162:    free_vector(tflin, 1, n);
                   4163:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   4164:    free_vector(e, 1, n);
                   4165:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   4166:    
                   4167:    return(fx);
                   4168: }
                   4169: 
                   4170: /* end praxis gegen */
1.126     brouard  4171: 
                   4172: /*************** powell ************************/
1.162     brouard  4173: /*
1.317     brouard  4174: Minimization of a function func of n variables. Input consists in an initial starting point
                   4175: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   4176: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   4177: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  4178: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   4179: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   4180:  */
1.224     brouard  4181: #ifdef LINMINORIGINAL
                   4182: #else
                   4183:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  4184:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  4185: #endif
1.126     brouard  4186: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   4187:            double (*func)(double [])) 
                   4188: { 
1.224     brouard  4189: #ifdef LINMINORIGINAL
                   4190:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  4191:              double (*func)(double [])); 
1.224     brouard  4192: #else 
1.241     brouard  4193:  void linmin(double p[], double xi[], int n, double *fret,
                   4194:             double (*func)(double []),int *flat); 
1.224     brouard  4195: #endif
1.239     brouard  4196:  int i,ibig,j,jk,k; 
1.126     brouard  4197:   double del,t,*pt,*ptt,*xit;
1.181     brouard  4198:   double directest;
1.126     brouard  4199:   double fp,fptt;
                   4200:   double *xits;
                   4201:   int niterf, itmp;
1.349     brouard  4202:   int Bigter=0, nBigterf=1;
                   4203:   
1.126     brouard  4204:   pt=vector(1,n); 
                   4205:   ptt=vector(1,n); 
                   4206:   xit=vector(1,n); 
                   4207:   xits=vector(1,n); 
                   4208:   *fret=(*func)(p); 
                   4209:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  4210:   rcurr_time = time(NULL);
                   4211:   fp=(*fret); /* Initialisation */
1.126     brouard  4212:   for (*iter=1;;++(*iter)) { 
                   4213:     ibig=0; 
                   4214:     del=0.0; 
1.157     brouard  4215:     rlast_time=rcurr_time;
1.349     brouard  4216:     rlast_btime=rcurr_time;
1.157     brouard  4217:     /* (void) gettimeofday(&curr_time,&tzp); */
                   4218:     rcurr_time = time(NULL);  
                   4219:     curr_time = *localtime(&rcurr_time);
1.337     brouard  4220:     /* 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); */
                   4221:     /* fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog); */
1.359     brouard  4222:     /* Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /\* Big iteration, i.e on ncovmodel cycle *\/ */
                   4223:     Bigter=(*iter - (*iter-1) % n)/n +1; /* Big iteration, i.e on ncovmodel cycle */
1.349     brouard  4224:     printf("\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   4225:     fprintf(ficlog,"\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   4226:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  4227:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  4228:     for (i=1;i<=n;i++) {
1.126     brouard  4229:       fprintf(ficrespow," %.12lf", p[i]);
                   4230:     }
1.239     brouard  4231:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   4232:     printf("\n#model=  1      +     age ");
                   4233:     fprintf(ficlog,"\n#model=  1      +     age ");
                   4234:     if(nagesqr==1){
1.241     brouard  4235:        printf("  + age*age  ");
                   4236:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  4237:     }
1.362     brouard  4238:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.239     brouard  4239:       if(Typevar[j]==0) {
                   4240:        printf("  +      V%d  ",Tvar[j]);
                   4241:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   4242:       }else if(Typevar[j]==1) {
                   4243:        printf("  +    V%d*age ",Tvar[j]);
                   4244:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   4245:       }else if(Typevar[j]==2) {
                   4246:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4247:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  4248:       }else if(Typevar[j]==3) {
                   4249:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4250:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  4251:       }
                   4252:     }
1.126     brouard  4253:     printf("\n");
1.239     brouard  4254: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   4255: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  4256:     fprintf(ficlog,"\n");
1.239     brouard  4257:     for(i=1,jk=1; i <=nlstate; i++){
                   4258:       for(k=1; k <=(nlstate+ndeath); k++){
                   4259:        if (k != i) {
                   4260:          printf("%d%d ",i,k);
                   4261:          fprintf(ficlog,"%d%d ",i,k);
                   4262:          for(j=1; j <=ncovmodel; j++){
                   4263:            printf("%12.7f ",p[jk]);
                   4264:            fprintf(ficlog,"%12.7f ",p[jk]);
                   4265:            jk++; 
                   4266:          }
                   4267:          printf("\n");
                   4268:          fprintf(ficlog,"\n");
                   4269:        }
                   4270:       }
                   4271:     }
1.241     brouard  4272:     if(*iter <=3 && *iter >1){
1.157     brouard  4273:       tml = *localtime(&rcurr_time);
                   4274:       strcpy(strcurr,asctime(&tml));
                   4275:       rforecast_time=rcurr_time; 
1.126     brouard  4276:       itmp = strlen(strcurr);
                   4277:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  4278:        strcurr[itmp-1]='\0';
1.162     brouard  4279:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  4280:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  4281:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   4282:        niterf=nBigterf*ncovmodel;
                   4283:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  4284:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   4285:        forecast_time = *localtime(&rforecast_time);
                   4286:        strcpy(strfor,asctime(&forecast_time));
                   4287:        itmp = strlen(strfor);
                   4288:        if(strfor[itmp-1]=='\n')
                   4289:          strfor[itmp-1]='\0';
1.349     brouard  4290:        printf("   - if your program needs %d BIG iterations (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   4291:        fprintf(ficlog,"   - if your program needs %d BIG iterations  (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  4292:       }
                   4293:     }
1.359     brouard  4294:     for (i=1;i<=n;i++) { /* For each direction i, maximisation after loading directions */
                   4295:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales. xi is not changed but one dim xit  */
                   4296: 
                   4297:       fptt=(*fret); /* Computes likelihood for parameters xit */
1.126     brouard  4298: #ifdef DEBUG
1.203     brouard  4299:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   4300:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  4301: #endif
1.203     brouard  4302:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  4303:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  4304: #ifdef LINMINORIGINAL
1.359     brouard  4305:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction xit, i has coordinates p[j].*/
1.357     brouard  4306:       /* xit[j] gives the n coordinates of direction i as input.*/
                   4307:       /* *fret gives the maximum value on direction xit */
1.224     brouard  4308: #else
                   4309:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.359     brouard  4310:       flatdir[i]=flat; /* Function is vanishing in that direction i */
1.224     brouard  4311: #endif
1.359     brouard  4312:       /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  4313:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.359     brouard  4314:        /* because that direction will be replaced unless the gain del is small */
                   4315:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   4316:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   4317:        /* with the new direction. */
                   4318:        del=fabs(fptt-(*fret)); 
                   4319:        ibig=i; 
1.126     brouard  4320:       } 
                   4321: #ifdef DEBUG
                   4322:       printf("%d %.12e",i,(*fret));
                   4323:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   4324:       for (j=1;j<=n;j++) {
1.359     brouard  4325:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   4326:        printf(" x(%d)=%.12e",j,xit[j]);
                   4327:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  4328:       }
                   4329:       for(j=1;j<=n;j++) {
1.359     brouard  4330:        printf(" p(%d)=%.12e",j,p[j]);
                   4331:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  4332:       }
                   4333:       printf("\n");
                   4334:       fprintf(ficlog,"\n");
                   4335: #endif
1.187     brouard  4336:     } /* end loop on each direction i */
1.357     brouard  4337:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  4338:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.359     brouard  4339:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  4340:     for(j=1;j<=n;j++) {
                   4341:       if(flatdir[j] >0){
                   4342:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   4343:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  4344:       }
1.319     brouard  4345:       /* printf("\n"); */
                   4346:       /* fprintf(ficlog,"\n"); */
                   4347:     }
1.243     brouard  4348:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   4349:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  4350:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   4351:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   4352:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   4353:       /* decreased of more than 3.84  */
                   4354:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   4355:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   4356:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  4357:                        
1.188     brouard  4358:       /* Starting the program with initial values given by a former maximization will simply change */
                   4359:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   4360:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   4361:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  4362: #ifdef DEBUG
                   4363:       int k[2],l;
                   4364:       k[0]=1;
                   4365:       k[1]=-1;
                   4366:       printf("Max: %.12e",(*func)(p));
                   4367:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   4368:       for (j=1;j<=n;j++) {
                   4369:        printf(" %.12e",p[j]);
                   4370:        fprintf(ficlog," %.12e",p[j]);
                   4371:       }
                   4372:       printf("\n");
                   4373:       fprintf(ficlog,"\n");
                   4374:       for(l=0;l<=1;l++) {
                   4375:        for (j=1;j<=n;j++) {
                   4376:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   4377:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4378:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4379:        }
                   4380:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4381:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4382:       }
                   4383: #endif
                   4384: 
                   4385:       free_vector(xit,1,n); 
                   4386:       free_vector(xits,1,n); 
                   4387:       free_vector(ptt,1,n); 
                   4388:       free_vector(pt,1,n); 
                   4389:       return; 
1.192     brouard  4390:     } /* enough precision */ 
1.240     brouard  4391:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.359     brouard  4392:     for (j=1;j<=n;j++) { /* Computes the extrapolated point and value f3, P_0 + 2 (P_n-P_0)=2Pn-P0 and xit is direction Pn-P0 */
1.126     brouard  4393:       ptt[j]=2.0*p[j]-pt[j]; 
1.359     brouard  4394:       xit[j]=p[j]-pt[j]; /* Coordinate j of last direction xi_n=P_n-P_0 */
                   4395: #ifdef DEBUG
                   4396:       printf("\n %d xit=%12.7g p=%12.7g pt=%12.7g ",j,xit[j],p[j],pt[j]);
                   4397: #endif
                   4398:       pt[j]=p[j]; /* New P0 is Pn */
                   4399:     }
                   4400: #ifdef DEBUG
                   4401:     printf("\n");
                   4402: #endif
1.181     brouard  4403:     fptt=(*func)(ptt); /* f_3 */
1.359     brouard  4404: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in directions until some iterations are done */
1.224     brouard  4405:                if (*iter <=4) {
1.225     brouard  4406: #else
                   4407: #endif
1.224     brouard  4408: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  4409: #else
1.161     brouard  4410:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  4411: #endif
1.162     brouard  4412:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  4413:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  4414:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   4415:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   4416:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  4417:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   4418:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   4419:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  4420:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  4421:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   4422:       /* mu² and del² are equal when f3=f1 */
1.359     brouard  4423:       /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   4424:       /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   4425:       /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   4426:       /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  4427: #ifdef NRCORIGINAL
                   4428:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   4429: #else
                   4430:       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  4431:       t= t- del*SQR(fp-fptt);
1.183     brouard  4432: #endif
1.202     brouard  4433:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  4434: #ifdef DEBUG
1.181     brouard  4435:       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);
                   4436:       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  4437:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4438:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4439:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4440:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4441:       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);
                   4442:       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);
                   4443: #endif
1.183     brouard  4444: #ifdef POWELLORIGINAL
                   4445:       if (t < 0.0) { /* Then we use it for new direction */
1.361     brouard  4446: #else  /* Not POWELLOriginal but Brouard's */
1.182     brouard  4447:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.359     brouard  4448:        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  4449:         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  4450:         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  4451:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   4452:       } 
1.361     brouard  4453:       if (directest < 0.0) { /* Then we use (P0, Pn) for new direction Xi_n or Xi_iBig */
1.181     brouard  4454: #endif
1.191     brouard  4455: #ifdef DEBUGLINMIN
1.234     brouard  4456:        printf("Before linmin in direction P%d-P0\n",n);
                   4457:        for (j=1;j<=n;j++) {
                   4458:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4459:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4460:          if(j % ncovmodel == 0){
                   4461:            printf("\n");
                   4462:            fprintf(ficlog,"\n");
                   4463:          }
                   4464:        }
1.224     brouard  4465: #endif
                   4466: #ifdef LINMINORIGINAL
1.234     brouard  4467:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  4468: #else
1.234     brouard  4469:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   4470:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  4471: #endif
1.234     brouard  4472:        
1.191     brouard  4473: #ifdef DEBUGLINMIN
1.234     brouard  4474:        for (j=1;j<=n;j++) { 
                   4475:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4476:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4477:          if(j % ncovmodel == 0){
                   4478:            printf("\n");
                   4479:            fprintf(ficlog,"\n");
                   4480:          }
                   4481:        }
1.224     brouard  4482: #endif
1.234     brouard  4483:        for (j=1;j<=n;j++) { 
                   4484:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   4485:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   4486:        }
1.361     brouard  4487: 
                   4488: /* #else */
                   4489: /*     for (i=1;i<=n-1;i++) {  */
                   4490: /*       for (j=1;j<=n;j++) {  */
                   4491: /*         xi[j][i]=xi[j][i+1]; /\* Standard method of conjugate directions, not Powell who changes the nth direction by p0 pn . *\/ */
                   4492: /*       } */
                   4493: /*     } */
                   4494: /*     for (j=1;j<=n;j++) {  */
                   4495: /*       xi[j][n]=xit[j];      /\* and this nth direction by the by the average p_0 p_n *\/ */
                   4496: /*     } */
                   4497: /*     /\* for (j=1;j<=n-1;j++) {  *\/ */
                   4498: /*     /\*   xi[j][1]=xi[j][j+1]; /\\* Standard method of conjugate directions *\\/ *\/ */
                   4499: /*     /\*   xi[j][n]=xit[j];      /\\* and this nth direction by the by the average p_0 p_n *\\/ *\/ */
                   4500: /*     /\* } *\/ */
                   4501: /* #endif */
1.224     brouard  4502: #ifdef LINMINORIGINAL
                   4503: #else
1.234     brouard  4504:        for (j=1, flatd=0;j<=n;j++) {
                   4505:          if(flatdir[j]>0)
                   4506:            flatd++;
                   4507:        }
                   4508:        if(flatd >0){
1.255     brouard  4509:          printf("%d flat directions: ",flatd);
                   4510:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  4511:          for (j=1;j<=n;j++) { 
                   4512:            if(flatdir[j]>0){
                   4513:              printf("%d ",j);
                   4514:              fprintf(ficlog,"%d ",j);
                   4515:            }
                   4516:          }
                   4517:          printf("\n");
                   4518:          fprintf(ficlog,"\n");
1.319     brouard  4519: #ifdef FLATSUP
                   4520:           free_vector(xit,1,n); 
                   4521:           free_vector(xits,1,n); 
                   4522:           free_vector(ptt,1,n); 
                   4523:           free_vector(pt,1,n); 
                   4524:           return;
                   4525: #endif
1.361     brouard  4526:        }  /* endif(flatd >0) */
                   4527: #endif /* LINMINORIGINAL */
1.234     brouard  4528:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4529:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4530:        
1.126     brouard  4531: #ifdef DEBUG
1.234     brouard  4532:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4533:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4534:        for(j=1;j<=n;j++){
                   4535:          printf(" %lf",xit[j]);
                   4536:          fprintf(ficlog," %lf",xit[j]);
                   4537:        }
                   4538:        printf("\n");
                   4539:        fprintf(ficlog,"\n");
1.126     brouard  4540: #endif
1.192     brouard  4541:       } /* end of t or directest negative */
1.359     brouard  4542:       printf(" Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
                   4543:       fprintf(ficlog," Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
1.224     brouard  4544: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  4545: #else
1.234     brouard  4546:       } /* end if (fptt < fp)  */
1.192     brouard  4547: #endif
1.225     brouard  4548: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  4549:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  4550: #else
1.224     brouard  4551: #endif
1.234     brouard  4552:                } /* loop iteration */ 
1.126     brouard  4553: } 
1.234     brouard  4554:   
1.126     brouard  4555: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  4556:   
1.235     brouard  4557:   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  4558:   {
1.338     brouard  4559:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  4560:      *   (and selected quantitative values in nres)
                   4561:      *  by left multiplying the unit
                   4562:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   4563:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   4564:      * Wx is row vector: population in state 1, population in state 2, population dead
                   4565:      * or prevalence in state 1, prevalence in state 2, 0
                   4566:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   4567:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   4568:      * Output is prlim.
                   4569:      * Initial matrix pimij 
                   4570:      */
1.206     brouard  4571:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4572:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4573:   /*  0,                   0                  , 1} */
                   4574:   /*
                   4575:    * and after some iteration: */
                   4576:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4577:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4578:   /*  0,                   0                  , 1} */
                   4579:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4580:   /* {0.51571254859325999, 0.4842874514067399, */
                   4581:   /*  0.51326036147820708, 0.48673963852179264} */
                   4582:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  4583:     
1.332     brouard  4584:     int i, ii,j,k, k1;
1.209     brouard  4585:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  4586:   /* double **matprod2(); */ /* test */
1.218     brouard  4587:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  4588:   double **newm;
1.209     brouard  4589:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  4590:   int ncvloop=0;
1.288     brouard  4591:   int first=0;
1.169     brouard  4592:   
1.209     brouard  4593:   min=vector(1,nlstate);
                   4594:   max=vector(1,nlstate);
                   4595:   meandiff=vector(1,nlstate);
                   4596: 
1.218     brouard  4597:        /* Starting with matrix unity */
1.126     brouard  4598:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4599:     for (j=1;j<=nlstate+ndeath;j++){
                   4600:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4601:     }
1.169     brouard  4602:   
                   4603:   cov[1]=1.;
                   4604:   
                   4605:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  4606:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  4607:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  4608:     ncvloop++;
1.126     brouard  4609:     newm=savm;
                   4610:     /* Covariates have to be included here again */
1.138     brouard  4611:     cov[2]=agefin;
1.319     brouard  4612:      if(nagesqr==1){
                   4613:       cov[3]= agefin*agefin;
                   4614:      }
1.332     brouard  4615:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   4616:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   4617:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4618:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4619:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4620:        }else{
                   4621:         cov[2+nagesqr+k1]=precov[nres][k1];
                   4622:        }
                   4623:      }/* End of loop on model equation */
                   4624:      
                   4625: /* Start of old code (replaced by a loop on position in the model equation */
                   4626:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   4627:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4628:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   4629:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   4630:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   4631:     /*    * k                  1        2      3    4      5      6     7        8 */
                   4632:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   4633:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   4634:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   4635:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   4636:     /*    *nsd=3                              (1)  (2)           (3) */
                   4637:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   4638:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   4639:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   4640:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   4641:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   4642:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   4643:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   4644:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   4645:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   4646:     /*    *TvarsDpType */
                   4647:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   4648:     /*    * nsd=1              (1)           (2) */
                   4649:     /*    *TvarsD[nsd]          3             2 */
                   4650:     /*    *TnsdVar           (3)=1          (2)=2 */
                   4651:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   4652:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   4653:     /*    *\/ */
                   4654:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   4655:     /*   /\* 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)); *\/ */
                   4656:     /* } */
                   4657:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   4658:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4659:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   4660:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   4661:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   4662:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4663:     /*   /\* 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]); *\/ */
                   4664:     /* } */
                   4665:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4666:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   4667:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4668:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   4669:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   4670:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4671:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4672:     /*   } */
                   4673:     /*   /\* 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]); *\/ */
                   4674:     /* } */
                   4675:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4676:     /*   /\* 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]); *\/ */
                   4677:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4678:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4679:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4680:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4681:     /*         }else{ */
                   4682:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4683:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   4684:     /*         } */
                   4685:     /*   }else{ */
                   4686:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4687:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4688:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   4689:     /*         }else{ */
                   4690:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4691:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   4692:     /*         } */
                   4693:     /*   } */
                   4694:     /* } /\* End product without age *\/ */
                   4695: /* ENd of old code */
1.138     brouard  4696:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4697:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4698:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  4699:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4700:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  4701:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  4702:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  4703:     
1.126     brouard  4704:     savm=oldm;
                   4705:     oldm=newm;
1.209     brouard  4706: 
                   4707:     for(j=1; j<=nlstate; j++){
                   4708:       max[j]=0.;
                   4709:       min[j]=1.;
                   4710:     }
                   4711:     for(i=1;i<=nlstate;i++){
                   4712:       sumnew=0;
                   4713:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   4714:       for(j=1; j<=nlstate; j++){ 
                   4715:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   4716:        max[j]=FMAX(max[j],prlim[i][j]);
                   4717:        min[j]=FMIN(min[j],prlim[i][j]);
                   4718:       }
                   4719:     }
                   4720: 
1.126     brouard  4721:     maxmax=0.;
1.209     brouard  4722:     for(j=1; j<=nlstate; j++){
                   4723:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   4724:       maxmax=FMAX(maxmax,meandiff[j]);
                   4725:       /* 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  4726:     } /* j loop */
1.203     brouard  4727:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  4728:     /* 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  4729:     if(maxmax < ftolpl){
1.209     brouard  4730:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   4731:       free_vector(min,1,nlstate);
                   4732:       free_vector(max,1,nlstate);
                   4733:       free_vector(meandiff,1,nlstate);
1.126     brouard  4734:       return prlim;
                   4735:     }
1.288     brouard  4736:   } /* agefin loop */
1.208     brouard  4737:     /* After some age loop it doesn't converge */
1.288     brouard  4738:   if(!first){
                   4739:     first=1;
                   4740:     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  4741:     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);
                   4742:   }else if (first >=1 && first <10){
                   4743:     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);
                   4744:     first++;
                   4745:   }else if (first ==10){
                   4746:     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);
                   4747:     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");
                   4748:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   4749:     first++;
1.288     brouard  4750:   }
                   4751: 
1.359     brouard  4752:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl,
                   4753:    * (int)age, (int)delaymax, (int)agefin, ncvloop,
                   4754:    * (int)age-(int)agefin); */
1.209     brouard  4755:   free_vector(min,1,nlstate);
                   4756:   free_vector(max,1,nlstate);
                   4757:   free_vector(meandiff,1,nlstate);
1.208     brouard  4758:   
1.169     brouard  4759:   return prlim; /* should not reach here */
1.126     brouard  4760: }
                   4761: 
1.217     brouard  4762: 
                   4763:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   4764: 
1.218     brouard  4765:  /* 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) */
                   4766:  /* 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  4767:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  4768: {
1.264     brouard  4769:   /* 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  4770:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   4771:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   4772:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   4773:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   4774:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   4775:   /* Initial matrix pimij */
                   4776:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4777:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4778:   /*  0,                   0                  , 1} */
                   4779:   /*
                   4780:    * and after some iteration: */
                   4781:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4782:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4783:   /*  0,                   0                  , 1} */
                   4784:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4785:   /* {0.51571254859325999, 0.4842874514067399, */
                   4786:   /*  0.51326036147820708, 0.48673963852179264} */
                   4787:   /* If we start from prlim again, prlim tends to a constant matrix */
                   4788: 
1.359     brouard  4789:   int i, ii,j, k1;
1.247     brouard  4790:   int first=0;
1.217     brouard  4791:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   4792:   /* double **matprod2(); */ /* test */
                   4793:   double **out, cov[NCOVMAX+1], **bmij();
                   4794:   double **newm;
1.218     brouard  4795:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   4796:   double        **oldm, **savm;  /* for use */
                   4797: 
1.217     brouard  4798:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   4799:   int ncvloop=0;
                   4800:   
                   4801:   min=vector(1,nlstate);
                   4802:   max=vector(1,nlstate);
                   4803:   meandiff=vector(1,nlstate);
                   4804: 
1.266     brouard  4805:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   4806:   oldm=oldms; savm=savms;
                   4807:   
                   4808:   /* Starting with matrix unity */
                   4809:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4810:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  4811:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4812:     }
                   4813:   
                   4814:   cov[1]=1.;
                   4815:   
                   4816:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4817:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  4818:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  4819:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   4820:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  4821:     ncvloop++;
1.218     brouard  4822:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   4823:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  4824:     /* Covariates have to be included here again */
                   4825:     cov[2]=agefin;
1.319     brouard  4826:     if(nagesqr==1){
1.217     brouard  4827:       cov[3]= agefin*agefin;;
1.319     brouard  4828:     }
1.332     brouard  4829:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4830:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4831:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  4832:       }else{
1.332     brouard  4833:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  4834:       }
1.332     brouard  4835:     }/* End of loop on model equation */
                   4836: 
                   4837: /* Old code */ 
                   4838: 
                   4839:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   4840:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4841:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   4842:     /*   /\* 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)); *\/ */
                   4843:     /* } */
                   4844:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   4845:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4846:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4847:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   4848:     /* /\* } *\/ */
                   4849:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4850:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4851:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4852:     /*   /\* 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]); *\/ */
                   4853:     /* } */
                   4854:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   4855:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   4856:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   4857:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4858:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4859:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   4860:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4861:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4862:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4863:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4864:     /*   } */
                   4865:     /*   /\* 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]); *\/ */
                   4866:     /* } */
                   4867:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4868:     /*   /\* 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]); *\/ */
                   4869:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4870:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4871:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4872:     /*         }else{ */
                   4873:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4874:     /*         } */
                   4875:     /*   }else{ */
                   4876:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4877:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4878:     /*         }else{ */
                   4879:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4880:     /*         } */
                   4881:     /*   } */
                   4882:     /* } */
1.217     brouard  4883:     
                   4884:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4885:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4886:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   4887:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4888:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  4889:                /* ij should be linked to the correct index of cov */
                   4890:                /* age and covariate values ij are in 'cov', but we need to pass
                   4891:                 * ij for the observed prevalence at age and status and covariate
                   4892:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   4893:                 */
                   4894:     /* 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 *\/ */
                   4895:     /* 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 *\/ */
                   4896:     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  4897:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  4898:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   4899:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   4900:     /*         printf("%d newm= ",i); */
                   4901:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4902:     /*           printf("%f ",newm[i][j]); */
                   4903:     /*         } */
                   4904:     /*         printf("oldm * "); */
                   4905:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4906:     /*           printf("%f ",oldm[i][j]); */
                   4907:     /*         } */
1.268     brouard  4908:     /*         printf(" bmmij "); */
1.266     brouard  4909:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4910:     /*           printf("%f ",pmmij[i][j]); */
                   4911:     /*         } */
                   4912:     /*         printf("\n"); */
                   4913:     /*   } */
                   4914:     /* } */
1.217     brouard  4915:     savm=oldm;
                   4916:     oldm=newm;
1.266     brouard  4917: 
1.217     brouard  4918:     for(j=1; j<=nlstate; j++){
                   4919:       max[j]=0.;
                   4920:       min[j]=1.;
                   4921:     }
                   4922:     for(j=1; j<=nlstate; j++){ 
                   4923:       for(i=1;i<=nlstate;i++){
1.234     brouard  4924:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   4925:        bprlim[i][j]= newm[i][j];
                   4926:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   4927:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  4928:       }
                   4929:     }
1.218     brouard  4930:                
1.217     brouard  4931:     maxmax=0.;
                   4932:     for(i=1; i<=nlstate; i++){
1.318     brouard  4933:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  4934:       maxmax=FMAX(maxmax,meandiff[i]);
                   4935:       /* 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  4936:     } /* i loop */
1.217     brouard  4937:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  4938:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4939:     if(maxmax < ftolpl){
1.220     brouard  4940:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4941:       free_vector(min,1,nlstate);
                   4942:       free_vector(max,1,nlstate);
                   4943:       free_vector(meandiff,1,nlstate);
                   4944:       return bprlim;
                   4945:     }
1.288     brouard  4946:   } /* agefin loop */
1.217     brouard  4947:     /* After some age loop it doesn't converge */
1.288     brouard  4948:   if(!first){
1.247     brouard  4949:     first=1;
                   4950:     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\
                   4951: 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);
                   4952:   }
                   4953:   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  4954: 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);
                   4955:   /* 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); */
                   4956:   free_vector(min,1,nlstate);
                   4957:   free_vector(max,1,nlstate);
                   4958:   free_vector(meandiff,1,nlstate);
                   4959:   
                   4960:   return bprlim; /* should not reach here */
                   4961: }
                   4962: 
1.126     brouard  4963: /*************** transition probabilities ***************/ 
                   4964: 
                   4965: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   4966: {
1.138     brouard  4967:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  4968:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  4969:      model to the ncovmodel covariates (including constant and age).
                   4970:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   4971:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   4972:      ncth covariate in the global vector x is given by the formula:
                   4973:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   4974:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   4975:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   4976:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  4977:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  4978:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  4979:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  4980:   */
                   4981:   double s1, lnpijopii;
1.126     brouard  4982:   /*double t34;*/
1.164     brouard  4983:   int i,j, nc, ii, jj;
1.126     brouard  4984: 
1.223     brouard  4985:   for(i=1; i<= nlstate; i++){
                   4986:     for(j=1; j<i;j++){
                   4987:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4988:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   4989:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   4990:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   4991:       }
                   4992:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4993:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4994:     }
                   4995:     for(j=i+1; j<=nlstate+ndeath;j++){
                   4996:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4997:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   4998:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   4999:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5000:       }
                   5001:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  5002:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  5003:     }
                   5004:   }
1.218     brouard  5005:   
1.223     brouard  5006:   for(i=1; i<= nlstate; i++){
                   5007:     s1=0;
                   5008:     for(j=1; j<i; j++){
1.339     brouard  5009:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  5010:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5011:     }
                   5012:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  5013:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  5014:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5015:     }
                   5016:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5017:     ps[i][i]=1./(s1+1.);
                   5018:     /* Computing other pijs */
                   5019:     for(j=1; j<i; j++)
1.325     brouard  5020:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  5021:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5022:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5023:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5024:   } /* end i */
1.218     brouard  5025:   
1.223     brouard  5026:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5027:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5028:       ps[ii][jj]=0;
                   5029:       ps[ii][ii]=1;
                   5030:     }
                   5031:   }
1.294     brouard  5032: 
                   5033: 
1.223     brouard  5034:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5035:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5036:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5037:   /*   } */
                   5038:   /*   printf("\n "); */
                   5039:   /* } */
                   5040:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5041:   /*
                   5042:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  5043:                goto end;*/
1.266     brouard  5044:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  5045: }
                   5046: 
1.218     brouard  5047: /*************** backward transition probabilities ***************/ 
                   5048: 
                   5049:  /* 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 ) */
                   5050: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   5051:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   5052: {
1.302     brouard  5053:   /* 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  5054:    * 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  5055:    */
1.359     brouard  5056:   int ii, j;
1.222     brouard  5057:   
1.359     brouard  5058:   double  **pmij();
1.222     brouard  5059:   double sumnew=0.;
1.218     brouard  5060:   double agefin;
1.292     brouard  5061:   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  5062:   double **dnewm, **dsavm, **doldm;
                   5063:   double **bbmij;
                   5064:   
1.218     brouard  5065:   doldm=ddoldms; /* global pointers */
1.222     brouard  5066:   dnewm=ddnewms;
                   5067:   dsavm=ddsavms;
1.318     brouard  5068: 
                   5069:   /* Debug */
                   5070:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  5071:   agefin=cov[2];
1.268     brouard  5072:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  5073:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  5074:      the observed prevalence (with this covariate ij) at beginning of transition */
                   5075:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  5076: 
                   5077:   /* P_x */
1.325     brouard  5078:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  5079:   /* outputs pmmij which is a stochastic matrix in row */
                   5080: 
                   5081:   /* Diag(w_x) */
1.292     brouard  5082:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  5083:   sumnew=0.;
1.269     brouard  5084:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  5085:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  5086:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  5087:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   5088:   }
                   5089:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   5090:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5091:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  5092:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  5093:     }
                   5094:   }else{
                   5095:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5096:       for (j=1;j<=nlstate+ndeath;j++)
                   5097:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   5098:     }
                   5099:     /* if(sumnew <0.9){ */
                   5100:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   5101:     /* } */
                   5102:   }
                   5103:   k3=0.0;  /* We put the last diagonal to 0 */
                   5104:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   5105:       doldm[ii][ii]= k3;
                   5106:   }
                   5107:   /* End doldm, At the end doldm is diag[(w_i)] */
                   5108:   
1.292     brouard  5109:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   5110:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  5111: 
1.292     brouard  5112:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  5113:   /* 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  5114:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  5115:     sumnew=0.;
1.222     brouard  5116:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  5117:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  5118:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  5119:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  5120:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  5121:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  5122:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5123:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  5124:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5125:        /* }else */
1.268     brouard  5126:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   5127:     } /*End ii */
                   5128:   } /* 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 */
                   5129: 
1.292     brouard  5130:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  5131:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  5132:   /* end bmij */
1.266     brouard  5133:   return ps; /*pointer is unchanged */
1.218     brouard  5134: }
1.217     brouard  5135: /*************** transition probabilities ***************/ 
                   5136: 
1.218     brouard  5137: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  5138: {
                   5139:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   5140:      computes the probability to be observed in state j being in state i by appying the
                   5141:      model to the ncovmodel covariates (including constant and age).
                   5142:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   5143:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   5144:      ncth covariate in the global vector x is given by the formula:
                   5145:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   5146:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   5147:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   5148:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   5149:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   5150:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   5151:   */
                   5152:   double s1, lnpijopii;
                   5153:   /*double t34;*/
                   5154:   int i,j, nc, ii, jj;
                   5155: 
1.234     brouard  5156:   for(i=1; i<= nlstate; i++){
                   5157:     for(j=1; j<i;j++){
                   5158:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5159:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   5160:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   5161:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5162:       }
                   5163:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5164:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5165:     }
                   5166:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5167:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5168:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5169:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5170:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5171:       }
                   5172:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5173:     }
                   5174:   }
                   5175:   
                   5176:   for(i=1; i<= nlstate; i++){
                   5177:     s1=0;
                   5178:     for(j=1; j<i; j++){
                   5179:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5180:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5181:     }
                   5182:     for(j=i+1; j<=nlstate+ndeath; j++){
                   5183:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5184:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5185:     }
                   5186:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5187:     ps[i][i]=1./(s1+1.);
                   5188:     /* Computing other pijs */
                   5189:     for(j=1; j<i; j++)
                   5190:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5191:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5192:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5193:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5194:   } /* end i */
                   5195:   
                   5196:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5197:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5198:       ps[ii][jj]=0;
                   5199:       ps[ii][ii]=1;
                   5200:     }
                   5201:   }
1.296     brouard  5202:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  5203:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5204:     s1=0.;
                   5205:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   5206:       s1+=ps[ii][jj];
                   5207:     }
                   5208:     for(ii=1; ii<= nlstate; ii++){
                   5209:       ps[ii][jj]=ps[ii][jj]/s1;
                   5210:     }
                   5211:   }
                   5212:   /* Transposition */
                   5213:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5214:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   5215:       s1=ps[ii][jj];
                   5216:       ps[ii][jj]=ps[jj][ii];
                   5217:       ps[jj][ii]=s1;
                   5218:     }
                   5219:   }
                   5220:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5221:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5222:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5223:   /*   } */
                   5224:   /*   printf("\n "); */
                   5225:   /* } */
                   5226:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5227:   /*
                   5228:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   5229:     goto end;*/
                   5230:   return ps;
1.217     brouard  5231: }
                   5232: 
                   5233: 
1.126     brouard  5234: /**************** Product of 2 matrices ******************/
                   5235: 
1.145     brouard  5236: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  5237: {
                   5238:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   5239:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   5240:   /* in, b, out are matrice of pointers which should have been initialized 
                   5241:      before: only the contents of out is modified. The function returns
                   5242:      a pointer to pointers identical to out */
1.145     brouard  5243:   int i, j, k;
1.126     brouard  5244:   for(i=nrl; i<= nrh; i++)
1.145     brouard  5245:     for(k=ncolol; k<=ncoloh; k++){
                   5246:       out[i][k]=0.;
                   5247:       for(j=ncl; j<=nch; j++)
                   5248:        out[i][k] +=in[i][j]*b[j][k];
                   5249:     }
1.126     brouard  5250:   return out;
                   5251: }
                   5252: 
                   5253: 
                   5254: /************* Higher Matrix Product ***************/
                   5255: 
1.235     brouard  5256: 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  5257: {
1.336     brouard  5258:   /* Already optimized with precov.
                   5259:      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  5260:      'nhstepm*hstepm*stepm' months (i.e. until
                   5261:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   5262:      nhstepm*hstepm matrices. 
                   5263:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   5264:      (typically every 2 years instead of every month which is too big 
                   5265:      for the memory).
                   5266:      Model is determined by parameters x and covariates have to be 
                   5267:      included manually here. 
                   5268: 
                   5269:      */
                   5270: 
1.359     brouard  5271:   int i, j, d, h, k1;
1.131     brouard  5272:   double **out, cov[NCOVMAX+1];
1.126     brouard  5273:   double **newm;
1.187     brouard  5274:   double agexact;
1.359     brouard  5275:   /*double agebegin, ageend;*/
1.126     brouard  5276: 
                   5277:   /* Hstepm could be zero and should return the unit matrix */
                   5278:   for (i=1;i<=nlstate+ndeath;i++)
                   5279:     for (j=1;j<=nlstate+ndeath;j++){
                   5280:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5281:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5282:     }
                   5283:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5284:   for(h=1; h <=nhstepm; h++){
                   5285:     for(d=1; d <=hstepm; d++){
                   5286:       newm=savm;
                   5287:       /* Covariates have to be included here again */
                   5288:       cov[1]=1.;
1.214     brouard  5289:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  5290:       cov[2]=agexact;
1.319     brouard  5291:       if(nagesqr==1){
1.227     brouard  5292:        cov[3]= agexact*agexact;
1.319     brouard  5293:       }
1.330     brouard  5294:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   5295:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   5296:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5297:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5298:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   5299:        }else{
                   5300:          cov[2+nagesqr+k1]=precov[nres][k1];
                   5301:        }
                   5302:       }/* End of loop on model equation */
                   5303:        /* Old code */ 
                   5304: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   5305: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   5306: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   5307: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   5308: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   5309: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5310: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5311: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   5312: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   5313: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   5314: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   5315: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   5316: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   5317: /*       /\* 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]])); *\/ */
                   5318: /*       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); */
                   5319: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5320: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   5321: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   5322: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   5323: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   5324: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   5325: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   5326: /*       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]]); */
                   5327: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5328: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   5329: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   5330: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   5331: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   5332: /*       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]); */
                   5333: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5334: 
                   5335: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   5336: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   5337: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   5338: /*       /\* *\/ */
1.330     brouard  5339: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5340: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5341: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  5342: /* /\*cptcovage=2                   1               2      *\/ */
                   5343: /* /\*Tage[k]=                      5               8      *\/  */
                   5344: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   5345: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   5346: /*       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]]); */
                   5347: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5348: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   5349: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   5350: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   5351: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   5352: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   5353: /*       /\*   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); *\/ */
                   5354: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   5355: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   5356: /*       /\* } *\/ */
                   5357: /*       /\* 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]); *\/ */
                   5358: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   5359: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   5360: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   5361: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   5362: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   5363: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   5364: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   5365: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   5366: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  5367:          
1.332     brouard  5368: /*       /\* 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])]); *\/ */
                   5369: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5370: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   5371: /*       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]]); */
                   5372: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5373: 
                   5374: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   5375: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   5376: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5377: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   5378: /*           /\* 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]])]; *\/ */
                   5379: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   5380: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   5381: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   5382: /*       /\*   } *\/ */
                   5383: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   5384: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   5385: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   5386: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5387: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   5388: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   5389: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5390: /*       /\*   } *\/ */
                   5391: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   5392: /*     }/\*end of products *\/ */
                   5393:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  5394:       /* for (k=1; k<=cptcovn;k++)  */
                   5395:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   5396:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   5397:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   5398:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   5399:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  5400:       
                   5401:       
1.126     brouard  5402:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   5403:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  5404:       /* right multiplication of oldm by the current matrix */
1.126     brouard  5405:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   5406:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  5407:       /* if((int)age == 70){ */
                   5408:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5409:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5410:       /*         printf("%d pmmij ",i); */
                   5411:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5412:       /*           printf("%f ",pmmij[i][j]); */
                   5413:       /*         } */
                   5414:       /*         printf(" oldm "); */
                   5415:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5416:       /*           printf("%f ",oldm[i][j]); */
                   5417:       /*         } */
                   5418:       /*         printf("\n"); */
                   5419:       /*       } */
                   5420:       /* } */
1.126     brouard  5421:       savm=oldm;
                   5422:       oldm=newm;
                   5423:     }
                   5424:     for(i=1; i<=nlstate+ndeath; i++)
                   5425:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  5426:        po[i][j][h]=newm[i][j];
                   5427:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  5428:       }
1.128     brouard  5429:     /*printf("h=%d ",h);*/
1.126     brouard  5430:   } /* end h */
1.267     brouard  5431:   /*     printf("\n H=%d \n",h); */
1.126     brouard  5432:   return po;
                   5433: }
                   5434: 
1.217     brouard  5435: /************* Higher Back Matrix Product ***************/
1.218     brouard  5436: /* 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  5437: 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  5438: {
1.332     brouard  5439:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   5440:      computes the transition matrix starting at age 'age' over
1.217     brouard  5441:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  5442:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   5443:      nhstepm*hstepm matrices.
                   5444:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   5445:      (typically every 2 years instead of every month which is too big
1.217     brouard  5446:      for the memory).
1.218     brouard  5447:      Model is determined by parameters x and covariates have to be
1.266     brouard  5448:      included manually here. Then we use a call to bmij(x and cov)
                   5449:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  5450:   */
1.217     brouard  5451: 
1.359     brouard  5452:   int i, j, d, h, k1;
1.266     brouard  5453:   double **out, cov[NCOVMAX+1], **bmij();
                   5454:   double **newm, ***newmm;
1.217     brouard  5455:   double agexact;
1.359     brouard  5456:   /*double agebegin, ageend;*/
1.222     brouard  5457:   double **oldm, **savm;
1.217     brouard  5458: 
1.266     brouard  5459:   newmm=po; /* To be saved */
                   5460:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  5461:   /* Hstepm could be zero and should return the unit matrix */
                   5462:   for (i=1;i<=nlstate+ndeath;i++)
                   5463:     for (j=1;j<=nlstate+ndeath;j++){
                   5464:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5465:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5466:     }
                   5467:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5468:   for(h=1; h <=nhstepm; h++){
                   5469:     for(d=1; d <=hstepm; d++){
                   5470:       newm=savm;
                   5471:       /* Covariates have to be included here again */
                   5472:       cov[1]=1.;
1.271     brouard  5473:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  5474:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  5475:         /* Debug */
                   5476:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  5477:       cov[2]=agexact;
1.332     brouard  5478:       if(nagesqr==1){
1.222     brouard  5479:        cov[3]= agexact*agexact;
1.332     brouard  5480:       }
                   5481:       /** New code */
                   5482:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5483:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5484:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  5485:        }else{
1.332     brouard  5486:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  5487:        }
1.332     brouard  5488:       }/* End of loop on model equation */
                   5489:       /** End of new code */
                   5490:   /** This was old code */
                   5491:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   5492:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   5493:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   5494:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   5495:       /*   /\* 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)); *\/ */
                   5496:       /* } */
                   5497:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   5498:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   5499:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   5500:       /*       /\* 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]); *\/ */
                   5501:       /* } */
                   5502:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   5503:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   5504:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   5505:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   5506:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   5507:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   5508:       /*       } */
                   5509:       /*       /\* 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]); *\/ */
                   5510:       /* } */
                   5511:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   5512:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   5513:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   5514:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5515:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   5516:       /*         }else{ */
                   5517:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   5518:       /*         } */
                   5519:       /*       }else{ */
                   5520:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5521:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   5522:       /*         }else{ */
                   5523:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   5524:       /*         } */
                   5525:       /*       } */
                   5526:       /* }                      */
                   5527:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   5528:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   5529: /** End of old code */
                   5530:       
1.218     brouard  5531:       /* Careful transposed matrix */
1.266     brouard  5532:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  5533:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  5534:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  5535:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  5536:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  5537:       /* if((int)age == 70){ */
                   5538:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5539:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5540:       /*         printf("%d pmmij ",i); */
                   5541:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5542:       /*           printf("%f ",pmmij[i][j]); */
                   5543:       /*         } */
                   5544:       /*         printf(" oldm "); */
                   5545:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5546:       /*           printf("%f ",oldm[i][j]); */
                   5547:       /*         } */
                   5548:       /*         printf("\n"); */
                   5549:       /*       } */
                   5550:       /* } */
                   5551:       savm=oldm;
                   5552:       oldm=newm;
                   5553:     }
                   5554:     for(i=1; i<=nlstate+ndeath; i++)
                   5555:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  5556:        po[i][j][h]=newm[i][j];
1.268     brouard  5557:        /* if(h==nhstepm) */
                   5558:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  5559:       }
1.268     brouard  5560:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  5561:   } /* end h */
1.268     brouard  5562:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  5563:   return po;
                   5564: }
                   5565: 
                   5566: 
1.162     brouard  5567: #ifdef NLOPT
                   5568:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   5569:   double fret;
                   5570:   double *xt;
                   5571:   int j;
                   5572:   myfunc_data *d2 = (myfunc_data *) pd;
                   5573: /* xt = (p1-1); */
                   5574:   xt=vector(1,n); 
                   5575:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   5576: 
                   5577:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   5578:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   5579:   printf("Function = %.12lf ",fret);
                   5580:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   5581:   printf("\n");
                   5582:  free_vector(xt,1,n);
                   5583:   return fret;
                   5584: }
                   5585: #endif
1.126     brouard  5586: 
                   5587: /*************** log-likelihood *************/
                   5588: double func( double *x)
                   5589: {
1.336     brouard  5590:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  5591:   int ioffset=0;
1.339     brouard  5592:   int ipos=0,iposold=0,ncovv=0;
                   5593: 
1.340     brouard  5594:   double cotvarv, cotvarvold;
1.226     brouard  5595:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   5596:   double **out;
                   5597:   double lli; /* Individual log likelihood */
                   5598:   int s1, s2;
1.228     brouard  5599:   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  5600: 
1.226     brouard  5601:   double bbh, survp;
                   5602:   double agexact;
1.336     brouard  5603:   double agebegin, ageend;
1.226     brouard  5604:   /*extern weight */
                   5605:   /* We are differentiating ll according to initial status */
                   5606:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5607:   /*for(i=1;i<imx;i++) 
                   5608:     printf(" %d\n",s[4][i]);
                   5609:   */
1.162     brouard  5610: 
1.226     brouard  5611:   ++countcallfunc;
1.162     brouard  5612: 
1.226     brouard  5613:   cov[1]=1.;
1.126     brouard  5614: 
1.226     brouard  5615:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5616:   ioffset=0;
1.226     brouard  5617:   if(mle==1){
                   5618:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5619:       /* Computes the values of the ncovmodel covariates of the model
                   5620:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5621:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5622:         to be observed in j being in i according to the model.
                   5623:       */
1.243     brouard  5624:       ioffset=2+nagesqr ;
1.233     brouard  5625:    /* Fixed */
1.345     brouard  5626:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  5627:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   5628:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   5629:        /*  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  5630:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  5631:        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  5632:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  5633:       }
1.226     brouard  5634:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  5635:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  5636:         has been calculated etc */
                   5637:       /* For an individual i, wav[i] gives the number of effective waves */
                   5638:       /* We compute the contribution to Likelihood of each effective transition
                   5639:         mw[mi][i] is real wave of the mi th effectve wave */
                   5640:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   5641:         s2=s[mw[mi+1][i]][i];
1.341     brouard  5642:         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  5643:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   5644:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   5645:       */
1.336     brouard  5646:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   5647:       /* Wave varying (but not age varying) */
1.339     brouard  5648:        /* 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*\/ */
                   5649:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   5650:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   5651:        /* } */
1.340     brouard  5652:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   5653:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5654:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  5655:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  5656:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  5657:          }else{ /* fixed covariate */
1.345     brouard  5658:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
1.340     brouard  5659:          }
1.339     brouard  5660:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  5661:            cotvarvold=cotvarv;
                   5662:          }else{ /* A second product */
                   5663:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  5664:          }
                   5665:          iposold=ipos;
1.340     brouard  5666:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  5667:        }
1.339     brouard  5668:        /* for products of time varying to be done */
1.234     brouard  5669:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5670:          for (j=1;j<=nlstate+ndeath;j++){
                   5671:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5672:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5673:          }
1.336     brouard  5674: 
                   5675:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   5676:        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  5677:        for(d=0; d<dh[mi][i]; d++){
                   5678:          newm=savm;
                   5679:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5680:          cov[2]=agexact;
                   5681:          if(nagesqr==1)
                   5682:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  5683:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   5684:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   5685:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   5686:          /*   else */
                   5687:          /*     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) *\/  */
                   5688:          /* } */
                   5689:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5690:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5691:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5692:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5693:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5694:            }else{ /* fixed covariate */
                   5695:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5696:            }
                   5697:            if(ipos!=iposold){ /* Not a product or first of a product */
                   5698:              cotvarvold=cotvarv;
                   5699:            }else{ /* A second product */
                   5700:              cotvarv=cotvarv*cotvarvold;
                   5701:            }
                   5702:            iposold=ipos;
                   5703:            cov[ioffset+ipos]=cotvarv*agexact;
                   5704:            /* For products */
1.234     brouard  5705:          }
1.349     brouard  5706:          
1.234     brouard  5707:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5708:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5709:          savm=oldm;
                   5710:          oldm=newm;
                   5711:        } /* end mult */
                   5712:        
                   5713:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   5714:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   5715:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   5716:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   5717:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   5718:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   5719:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   5720:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  5721:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   5722:                                 * -stepm/2 to stepm/2 .
                   5723:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   5724:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   5725:                                 */
1.234     brouard  5726:        s1=s[mw[mi][i]][i];
                   5727:        s2=s[mw[mi+1][i]][i];
                   5728:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5729:        /* bias bh is positive if real duration
                   5730:         * is higher than the multiple of stepm and negative otherwise.
                   5731:         */
                   5732:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   5733:        if( s2 > nlstate){ 
                   5734:          /* i.e. if s2 is a death state and if the date of death is known 
                   5735:             then the contribution to the likelihood is the probability to 
                   5736:             die between last step unit time and current  step unit time, 
                   5737:             which is also equal to probability to die before dh 
                   5738:             minus probability to die before dh-stepm . 
                   5739:             In version up to 0.92 likelihood was computed
                   5740:             as if date of death was unknown. Death was treated as any other
                   5741:             health state: the date of the interview describes the actual state
                   5742:             and not the date of a change in health state. The former idea was
                   5743:             to consider that at each interview the state was recorded
                   5744:             (healthy, disable or death) and IMaCh was corrected; but when we
                   5745:             introduced the exact date of death then we should have modified
                   5746:             the contribution of an exact death to the likelihood. This new
                   5747:             contribution is smaller and very dependent of the step unit
                   5748:             stepm. It is no more the probability to die between last interview
                   5749:             and month of death but the probability to survive from last
                   5750:             interview up to one month before death multiplied by the
                   5751:             probability to die within a month. Thanks to Chris
                   5752:             Jackson for correcting this bug.  Former versions increased
                   5753:             mortality artificially. The bad side is that we add another loop
                   5754:             which slows down the processing. The difference can be up to 10%
                   5755:             lower mortality.
                   5756:          */
                   5757:          /* If, at the beginning of the maximization mostly, the
                   5758:             cumulative probability or probability to be dead is
                   5759:             constant (ie = 1) over time d, the difference is equal to
                   5760:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   5761:             s1 at precedent wave, to be dead a month before current
                   5762:             wave is equal to probability, being at state s1 at
                   5763:             precedent wave, to be dead at mont of the current
                   5764:             wave. Then the observed probability (that this person died)
                   5765:             is null according to current estimated parameter. In fact,
                   5766:             it should be very low but not zero otherwise the log go to
                   5767:             infinity.
                   5768:          */
1.183     brouard  5769: /* #ifdef INFINITYORIGINAL */
                   5770: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5771: /* #else */
                   5772: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   5773: /*         lli=log(mytinydouble); */
                   5774: /*       else */
                   5775: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5776: /* #endif */
1.226     brouard  5777:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  5778:          
1.226     brouard  5779:        } else if  ( s2==-1 ) { /* alive */
                   5780:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5781:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   5782:          /*survp += out[s1][j]; */
                   5783:          lli= log(survp);
                   5784:        }
1.336     brouard  5785:        /* else if  (s2==-4) {  */
                   5786:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   5787:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5788:        /*   lli= log(survp);  */
                   5789:        /* }  */
                   5790:        /* else if  (s2==-5) {  */
                   5791:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   5792:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5793:        /*   lli= log(survp);  */
                   5794:        /* }  */
1.226     brouard  5795:        else{
                   5796:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5797:          /*  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 */
                   5798:        } 
                   5799:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   5800:        /*if(lli ==000.0)*/
1.340     brouard  5801:        /* 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  5802:        ipmx +=1;
                   5803:        sw += weight[i];
                   5804:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5805:        /* if (lli < log(mytinydouble)){ */
                   5806:        /*   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); */
                   5807:        /*   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]); */
                   5808:        /* } */
                   5809:       } /* end of wave */
                   5810:     } /* end of individual */
                   5811:   }  else if(mle==2){
                   5812:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  5813:       ioffset=2+nagesqr ;
                   5814:       for (k=1; k<=ncovf;k++)
                   5815:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  5816:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  5817:        for(k=1; k <= ncovv ; k++){
1.341     brouard  5818:          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  5819:        }
1.226     brouard  5820:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5821:          for (j=1;j<=nlstate+ndeath;j++){
                   5822:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5823:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5824:          }
                   5825:        for(d=0; d<=dh[mi][i]; d++){
                   5826:          newm=savm;
                   5827:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5828:          cov[2]=agexact;
                   5829:          if(nagesqr==1)
                   5830:            cov[3]= agexact*agexact;
                   5831:          for (kk=1; kk<=cptcovage;kk++) {
                   5832:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5833:          }
                   5834:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5835:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5836:          savm=oldm;
                   5837:          oldm=newm;
                   5838:        } /* end mult */
                   5839:       
                   5840:        s1=s[mw[mi][i]][i];
                   5841:        s2=s[mw[mi+1][i]][i];
                   5842:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5843:        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 */
                   5844:        ipmx +=1;
                   5845:        sw += weight[i];
                   5846:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5847:       } /* end of wave */
                   5848:     } /* end of individual */
                   5849:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   5850:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5851:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5852:       for(mi=1; mi<= wav[i]-1; mi++){
                   5853:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5854:          for (j=1;j<=nlstate+ndeath;j++){
                   5855:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5856:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5857:          }
                   5858:        for(d=0; d<dh[mi][i]; d++){
                   5859:          newm=savm;
                   5860:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5861:          cov[2]=agexact;
                   5862:          if(nagesqr==1)
                   5863:            cov[3]= agexact*agexact;
                   5864:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5865:            if(!FixedV[Tvar[Tage[kk]]])
                   5866:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5867:            else
1.341     brouard  5868:              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  5869:          }
                   5870:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5871:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5872:          savm=oldm;
                   5873:          oldm=newm;
                   5874:        } /* end mult */
                   5875:       
                   5876:        s1=s[mw[mi][i]][i];
                   5877:        s2=s[mw[mi+1][i]][i];
                   5878:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5879:        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 */
                   5880:        ipmx +=1;
                   5881:        sw += weight[i];
                   5882:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5883:       } /* end of wave */
                   5884:     } /* end of individual */
                   5885:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   5886:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5887:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5888:       for(mi=1; mi<= wav[i]-1; mi++){
                   5889:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5890:          for (j=1;j<=nlstate+ndeath;j++){
                   5891:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5892:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5893:          }
                   5894:        for(d=0; d<dh[mi][i]; d++){
                   5895:          newm=savm;
                   5896:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5897:          cov[2]=agexact;
                   5898:          if(nagesqr==1)
                   5899:            cov[3]= agexact*agexact;
                   5900:          for (kk=1; kk<=cptcovage;kk++) {
                   5901:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5902:          }
1.126     brouard  5903:        
1.226     brouard  5904:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5905:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5906:          savm=oldm;
                   5907:          oldm=newm;
                   5908:        } /* end mult */
                   5909:       
                   5910:        s1=s[mw[mi][i]][i];
                   5911:        s2=s[mw[mi+1][i]][i];
                   5912:        if( s2 > nlstate){ 
                   5913:          lli=log(out[s1][s2] - savm[s1][s2]);
                   5914:        } else if  ( s2==-1 ) { /* alive */
                   5915:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5916:            survp += out[s1][j];
                   5917:          lli= log(survp);
                   5918:        }else{
                   5919:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5920:        }
                   5921:        ipmx +=1;
                   5922:        sw += weight[i];
                   5923:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  5924:        /* printf("num[i]=%09ld, i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.226     brouard  5925:       } /* end of wave */
                   5926:     } /* end of individual */
                   5927:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   5928:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5929:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5930:       for(mi=1; mi<= wav[i]-1; mi++){
                   5931:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5932:          for (j=1;j<=nlstate+ndeath;j++){
                   5933:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5934:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5935:          }
                   5936:        for(d=0; d<dh[mi][i]; d++){
                   5937:          newm=savm;
                   5938:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5939:          cov[2]=agexact;
                   5940:          if(nagesqr==1)
                   5941:            cov[3]= agexact*agexact;
                   5942:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5943:            if(!FixedV[Tvar[Tage[kk]]])
                   5944:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5945:            else
1.341     brouard  5946:              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  5947:          }
1.126     brouard  5948:        
1.226     brouard  5949:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5950:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5951:          savm=oldm;
                   5952:          oldm=newm;
                   5953:        } /* end mult */
                   5954:       
                   5955:        s1=s[mw[mi][i]][i];
                   5956:        s2=s[mw[mi+1][i]][i];
                   5957:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5958:        ipmx +=1;
                   5959:        sw += weight[i];
                   5960:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5961:        /*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]);*/
                   5962:       } /* end of wave */
                   5963:     } /* end of individual */
                   5964:   } /* End of if */
                   5965:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5966:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5967:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5968:   return -l;
1.126     brouard  5969: }
                   5970: 
                   5971: /*************** log-likelihood *************/
                   5972: double funcone( double *x)
                   5973: {
1.228     brouard  5974:   /* Same as func but slower because of a lot of printf and if */
1.359     brouard  5975:   int i, ii, j, k, mi, d, kv=0, kf=0;
1.228     brouard  5976:   int ioffset=0;
1.339     brouard  5977:   int ipos=0,iposold=0,ncovv=0;
                   5978: 
1.340     brouard  5979:   double cotvarv, cotvarvold;
1.131     brouard  5980:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  5981:   double **out;
                   5982:   double lli; /* Individual log likelihood */
                   5983:   double llt;
                   5984:   int s1, s2;
1.228     brouard  5985:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   5986: 
1.126     brouard  5987:   double bbh, survp;
1.187     brouard  5988:   double agexact;
1.214     brouard  5989:   double agebegin, ageend;
1.126     brouard  5990:   /*extern weight */
                   5991:   /* We are differentiating ll according to initial status */
                   5992:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5993:   /*for(i=1;i<imx;i++) 
                   5994:     printf(" %d\n",s[4][i]);
                   5995:   */
                   5996:   cov[1]=1.;
                   5997: 
                   5998:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5999:   ioffset=0;
                   6000:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  6001:     /* Computes the values of the ncovmodel covariates of the model
                   6002:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   6003:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   6004:        to be observed in j being in i according to the model.
                   6005:     */
1.243     brouard  6006:     /* ioffset=2+nagesqr+cptcovage; */
                   6007:     ioffset=2+nagesqr;
1.232     brouard  6008:     /* Fixed */
1.224     brouard  6009:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  6010:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  6011:     for (kf=1; kf<=ncovf;kf++){ /*  V2  +  V3  +  V4  Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  6012:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   6013:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   6014:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  6015:       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  6016: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   6017: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   6018: /*    cov[2+6]=covar[2][i]; V2  */
                   6019: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   6020: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   6021: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   6022: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   6023: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   6024: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  6025:     }
1.336     brouard  6026:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   6027:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   6028:         has been calculated etc */
                   6029:       /* For an individual i, wav[i] gives the number of effective waves */
                   6030:       /* We compute the contribution to Likelihood of each effective transition
                   6031:         mw[mi][i] is real wave of the mi th effectve wave */
                   6032:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   6033:         s2=s[mw[mi+1][i]][i];
1.341     brouard  6034:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  6035:       */
                   6036:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  6037:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   6038:     /*   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?)*\/ */
                   6039:     /* } */
1.231     brouard  6040:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   6041:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   6042:     /* } */
1.225     brouard  6043:     
1.233     brouard  6044: 
                   6045:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  6046:       /* 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 */
                   6047:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   6048:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   6049:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   6050:       /* } */
                   6051:       
                   6052:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   6053:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   6054:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   6055:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   6056:       /* We need the position of the time varying or product in the model */
                   6057:       /* 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 */            
                   6058:       /* TvarVV gives the variable name */
1.340     brouard  6059:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   6060:       *      k=         1   2     3     4         5        6        7       8        9
                   6061:       *  varying            1     2                                 3       4        5
                   6062:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  6063:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  6064:       * TvarVVind           2     3                                7 7     8 8      9 9
                   6065:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   6066:       */
1.345     brouard  6067:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  6068:        * V2 V3 V4 are fixed V6 V7 are timevarying so V8 and V5 are not in the model and product column will start at 9 Tvar[(v6*V2)6]=9
1.345     brouard  6069:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  6070:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   6071:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   6072:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   6073:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6074:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6075:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6076:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6077:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6078:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6079:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6080:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6081:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6082:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   6083:        *                  12       13      14      15       16
                   6084:        *                    17        18         19        20         21
                   6085:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   6086:        *                   2       3        4       6        7
                   6087:        *                     9         11          12        13         14            
                   6088:        * cptcovage=5+5 total of covariates with age 
                   6089:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   6090:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   6091:        *3 Tage[cptcovage] age*V3*V2=6  
                   6092:        *3                age*V2=12         13      14      15       16
                   6093:        *3                age*V6*V3=18      19    20   21
                   6094:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   6095:        *     Tvar[17]age*V6*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6096:        * 2   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6097:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   6098:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6099:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   6100:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   6101:        * 3   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6102:        * Tvar=                {2, 3, 4, 6, 7,
                   6103:        *                       9, 10, 11, 12, 13, 14,
                   6104:        *              Tvar[12]=2, 3, 4, 6, 7,
                   6105:        *              Tvar[17]=9, 11, 12, 13, 14}
                   6106:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   6107:        *                  2, 2, 2, 2, 2, 2,
                   6108:        * 3                3, 2, 2, 2, 2, 2,
                   6109:        *                  1, 1, 1, 1, 1, 
                   6110:        *                  3, 3, 3, 3, 3}
                   6111:        * 3                 2, 3, 3, 3, 3}
                   6112:        * p Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6} Id of the prod at position k in the model
                   6113:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6114:        * 3 Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6}
                   6115:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6116:        * cptcovprod=11 (6+5)
                   6117:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   6118:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   6119:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   6120:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   6121:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6122:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6123:        * cptcovdageprod=5  for gnuplot printing
                   6124:        * cptcovprodvage=6 
                   6125:        * ncova=15           1        2       3       4       5
                   6126:        *                      6 7        8 9      10 11        12 13     14 15
                   6127:        * TvarA              2        3       4       6       7
                   6128:        *                      6 2        6 7       7 3          6 4       7 4
                   6129:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  6130:        * ncovf            1     2      3
1.349     brouard  6131:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6132:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   6133:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6134:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   6135:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6136:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6137:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   6138:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   6139:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   6140:        * 3 cptcovprodvage=6
                   6141:        * 3 ncovta=15    +age*V3*V2+age*V2+agev3+ageV4 +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6142:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   6143:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  6144:        *?TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
1.349     brouard  6145:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   6146:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6147:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   6148:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   6149:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   6150:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   6151:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   6152:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  6153:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  6154:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   6155:        *                   2, 3, 4, 6, 7,
                   6156:        *                     6, 8, 9, 10, 11}
1.345     brouard  6157:        * TvarFind[itv]                        0      0       0
                   6158:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  6159:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  6160:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   6161:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   6162:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  6163:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  6164:        */
                   6165: 
1.349     brouard  6166:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /*  V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4 Time varying  covariates (single and extended product but no age) including individual from products, product is computed dynamically */
                   6167:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, or fixed covariate of a varying product after exploding product Vn*Vm into Vn and then Vm  */
1.340     brouard  6168:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  6169:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6170:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
1.354     brouard  6171:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  6172:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  6173:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6174:        }else{ /* fixed covariate */
1.345     brouard  6175:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
1.354     brouard  6176:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  6177:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  6178:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6179:        }
1.339     brouard  6180:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  6181:          cotvarvold=cotvarv;
                   6182:        }else{ /* A second product */
                   6183:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  6184:        }
                   6185:        iposold=ipos;
1.340     brouard  6186:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  6187:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  6188:        /* For products */
                   6189:       }
                   6190:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   6191:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   6192:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   6193:       /*       /\*           1  2   3      4      5                         *\/ */
                   6194:       /*       /\*itv           1                                           *\/ */
                   6195:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   6196:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   6197:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   6198:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   6199:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   6200:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   6201:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   6202:       /*       /\* 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]); *\/ */
                   6203:       /* } */
1.232     brouard  6204:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  6205:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   6206:       /*       /\* 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]); *\/ */
                   6207:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  6208:       /* } */
1.126     brouard  6209:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  6210:        for (j=1;j<=nlstate+ndeath;j++){
                   6211:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6212:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6213:        }
1.214     brouard  6214:       
                   6215:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   6216:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   6217:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  6218:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  6219:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6220:          and mw[mi+1][i]. dh depends on stepm.*/
                   6221:        newm=savm;
1.247     brouard  6222:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  6223:        cov[2]=agexact;
                   6224:        if(nagesqr==1)
                   6225:          cov[3]= agexact*agexact;
1.349     brouard  6226:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6227:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6228:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6229:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6230:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6231:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6232:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6233:          }else{ /* fixed covariate */
                   6234:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6235:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6236:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6237:          }
                   6238:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6239:            cotvarvold=cotvarv;
                   6240:          }else{ /* A second product */
                   6241:            /* printf("DEBUG * \n"); */
                   6242:            cotvarv=cotvarv*cotvarvold;
                   6243:          }
                   6244:          iposold=ipos;
                   6245:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6246:          cov[ioffset+ipos]=cotvarv*agexact;
                   6247:          /* For products */
1.242     brouard  6248:        }
1.349     brouard  6249: 
1.242     brouard  6250:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   6251:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   6252:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   6253:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   6254:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   6255:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   6256:        savm=oldm;
                   6257:        oldm=newm;
1.126     brouard  6258:       } /* end mult */
1.336     brouard  6259:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   6260:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   6261:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   6262:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   6263:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   6264:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   6265:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   6266:         * probability in order to take into account the bias as a fraction of the way
                   6267:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   6268:                                 * -stepm/2 to stepm/2 .
                   6269:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   6270:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   6271:                                 */
1.126     brouard  6272:       s1=s[mw[mi][i]][i];
                   6273:       s2=s[mw[mi+1][i]][i];
1.217     brouard  6274:       /* if(s2==-1){ */
1.268     brouard  6275:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  6276:       /*       /\* exit(1); *\/ */
                   6277:       /* } */
1.126     brouard  6278:       bbh=(double)bh[mi][i]/(double)stepm; 
                   6279:       /* bias is positive if real duration
                   6280:        * is higher than the multiple of stepm and negative otherwise.
                   6281:        */
                   6282:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  6283:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  6284:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  6285:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   6286:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   6287:        lli= log(survp);
1.126     brouard  6288:       }else if (mle==1){
1.242     brouard  6289:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  6290:       } else if(mle==2){
1.242     brouard  6291:        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  6292:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  6293:        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  6294:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  6295:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  6296:       } else{  /* mle=0 back to 1 */
1.242     brouard  6297:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   6298:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  6299:       } /* End of if */
                   6300:       ipmx +=1;
                   6301:       sw += weight[i];
                   6302:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  6303:       /* Printing covariates values for each contribution for checking */
1.343     brouard  6304:       /* printf("num[i]=%09ld, i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.126     brouard  6305:       if(globpr){
1.246     brouard  6306:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  6307:  %11.6f %11.6f %11.6f ", \
1.242     brouard  6308:                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  6309:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  6310:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   6311:        /* %11.6f %11.6f %11.6f ", \ */
                   6312:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   6313:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  6314:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   6315:          llt +=ll[k]*gipmx/gsw;
                   6316:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  6317:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  6318:        }
1.343     brouard  6319:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  6320:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  6321:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  6322:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   6323:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   6324:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   6325:        }
                   6326:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   6327:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6328:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6329:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   6330:            /* printf(" %g",cov[ioffset+ipos]); */
                   6331:          }else{
                   6332:            fprintf(ficresilk,"*");
                   6333:            /* printf("*"); */
1.342     brouard  6334:          }
1.343     brouard  6335:          iposold=ipos;
                   6336:        }
1.349     brouard  6337:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   6338:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   6339:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   6340:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   6341:        /*   }else{ */
                   6342:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6343:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   6344:        /*   } */
                   6345:        /* } */
                   6346:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6347:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6348:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6349:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6350:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6351:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6352:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6353:          }else{ /* fixed covariate */
                   6354:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6355:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6356:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6357:          }
                   6358:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6359:            cotvarvold=cotvarv;
                   6360:          }else{ /* A second product */
                   6361:            /* printf("DEBUG * \n"); */
                   6362:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  6363:          }
1.349     brouard  6364:          cotvarv=cotvarv*agexact;
                   6365:          fprintf(ficresilk," %g*age",cotvarv);
                   6366:          iposold=ipos;
                   6367:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6368:          cov[ioffset+ipos]=cotvarv;
                   6369:          /* For products */
1.343     brouard  6370:        }
                   6371:        /* printf("\n"); */
1.342     brouard  6372:        /* } /\*  End debugILK *\/ */
                   6373:        fprintf(ficresilk,"\n");
                   6374:       } /* End if globpr */
1.335     brouard  6375:     } /* end of wave */
                   6376:   } /* end of individual */
                   6377:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  6378: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  6379:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   6380:   if(globpr==0){ /* First time we count the contributions and weights */
                   6381:     gipmx=ipmx;
                   6382:     gsw=sw;
                   6383:   }
1.343     brouard  6384:   return -l;
1.126     brouard  6385: }
                   6386: 
                   6387: 
                   6388: /*************** function likelione ***********/
1.292     brouard  6389: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  6390: {
                   6391:   /* This routine should help understanding what is done with 
                   6392:      the selection of individuals/waves and
                   6393:      to check the exact contribution to the likelihood.
                   6394:      Plotting could be done.
1.342     brouard  6395:   */
                   6396:   void pstamp(FILE *ficres);
1.343     brouard  6397:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  6398: 
                   6399:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  6400:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  6401:     strcat(fileresilk,fileresu);
1.126     brouard  6402:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   6403:       printf("Problem with resultfile: %s\n", fileresilk);
                   6404:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   6405:     }
1.342     brouard  6406:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  6407:     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");
                   6408:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  6409:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   6410:     for(k=1; k<=nlstate; k++) 
                   6411:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  6412:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   6413: 
                   6414:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   6415:       for(kf=1;kf <= ncovf; kf++){
                   6416:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   6417:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   6418:       }
                   6419:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  6420:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  6421:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6422:          /* printf(" %d",ipos); */
                   6423:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   6424:        }else{
                   6425:          /* printf("*"); */
                   6426:          fprintf(ficresilk,"*");
1.343     brouard  6427:        }
1.342     brouard  6428:        iposold=ipos;
                   6429:       }
                   6430:       for (kk=1; kk<=cptcovage;kk++) {
                   6431:        if(!FixedV[Tvar[Tage[kk]]]){
                   6432:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   6433:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   6434:        }else{
                   6435:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6436:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6437:        }
                   6438:       }
                   6439:     /* } /\* End if debugILK *\/ */
                   6440:     /* printf("\n"); */
                   6441:     fprintf(ficresilk,"\n");
                   6442:   } /* End glogpri */
1.126     brouard  6443: 
1.292     brouard  6444:   *fretone=(*func)(p);
1.126     brouard  6445:   if(*globpri !=0){
                   6446:     fclose(ficresilk);
1.205     brouard  6447:     if (mle ==0)
                   6448:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   6449:     else if(mle >=1)
                   6450:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   6451:     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  6452:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  6453:       
1.207     brouard  6454:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.343     brouard  6455: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  6456:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  6457: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   6458:     
                   6459:     for (k=1; k<= nlstate ; k++) {
                   6460:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br>\n \
                   6461: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   6462:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  6463:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   6464:         fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): ",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]]);
                   6465:         fprintf(fichtm,"<a href=\"%s-p%dj-%d.png\">%s-p%dj-%d.png</a><br>",subdirf2(optionfilefiname,"ILK_"),k,kvar,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   6466:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  6467:       }
                   6468:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   6469:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   6470:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   6471:        /* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   6472:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6473:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   6474:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   6475:          if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   6476:            fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored time varying dummy covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   6477: <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   6478:          } /* End only for dummies time varying (single?) */
                   6479:        }else{ /* Useless product */
                   6480:          /* printf("*"); */
                   6481:          /* fprintf(ficresilk,"*"); */ 
                   6482:        }
                   6483:        iposold=ipos;
                   6484:       } /* For each time varying covariate */
                   6485:     } /* End loop on states */
                   6486: 
                   6487: /*     if(debugILK){ */
                   6488: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   6489: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   6490: /*     for (k=1; k<= nlstate ; k++) { */
                   6491: /*       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   6492: /* <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]); */
                   6493: /*     } */
                   6494: /*       } */
                   6495: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   6496: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   6497: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   6498: /*     /\* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); *\/ */
                   6499: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   6500: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   6501: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   6502: /*       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /\* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  *\/ */
                   6503: /*         for (k=1; k<= nlstate ; k++) { */
                   6504: /*           fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   6505: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   6506: /*         } /\* End state *\/ */
                   6507: /*       } /\* End only for dummies time varying (single?) *\/ */
                   6508: /*     }else{ /\* Useless product *\/ */
                   6509: /*       /\* printf("*"); *\/ */
                   6510: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   6511: /*     } */
                   6512: /*     iposold=ipos; */
                   6513: /*       } /\* For each time varying covariate *\/ */
                   6514: /*     }/\* End debugILK *\/ */
1.207     brouard  6515:     fflush(fichtm);
1.343     brouard  6516:   }/* End globpri */
1.126     brouard  6517:   return;
                   6518: }
                   6519: 
                   6520: 
                   6521: /*********** Maximum Likelihood Estimation ***************/
                   6522: 
                   6523: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   6524: {
1.359     brouard  6525:   int i,j,  jkk=0, iter=0;
1.126     brouard  6526:   double **xi;
1.359     brouard  6527:   /*double fret;*/
                   6528:   /*double fretone;*/ /* Only one call to likelihood */
1.126     brouard  6529:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  6530:   
1.359     brouard  6531:   /*double * p1;*/ /* Shifted parameters from 0 instead of 1 */
1.162     brouard  6532: #ifdef NLOPT
                   6533:   int creturn;
                   6534:   nlopt_opt opt;
                   6535:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   6536:   double *lb;
                   6537:   double minf; /* the minimum objective value, upon return */
1.354     brouard  6538: 
1.162     brouard  6539:   myfunc_data dinst, *d = &dinst;
                   6540: #endif
                   6541: 
                   6542: 
1.126     brouard  6543:   xi=matrix(1,npar,1,npar);
1.357     brouard  6544:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  6545:     for (j=1;j<=npar;j++)
                   6546:       xi[i][j]=(i==j ? 1.0 : 0.0);
1.359     brouard  6547:   printf("Powell-prax\n");  fprintf(ficlog,"Powell-prax\n");
1.201     brouard  6548:   strcpy(filerespow,"POW_"); 
1.126     brouard  6549:   strcat(filerespow,fileres);
                   6550:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6551:     printf("Problem with resultfile: %s\n", filerespow);
                   6552:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6553:   }
                   6554:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   6555:   for (i=1;i<=nlstate;i++)
                   6556:     for(j=1;j<=nlstate+ndeath;j++)
                   6557:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6558:   fprintf(ficrespow,"\n");
1.162     brouard  6559: #ifdef POWELL
1.319     brouard  6560: #ifdef LINMINORIGINAL
                   6561: #else /* LINMINORIGINAL */
                   6562:   
                   6563:   flatdir=ivector(1,npar); 
                   6564:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   6565: #endif /*LINMINORIGINAL */
                   6566: 
                   6567: #ifdef FLATSUP
                   6568:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6569:   /* reorganizing p by suppressing flat directions */
                   6570:   for(i=1, jk=1; i <=nlstate; i++){
                   6571:     for(k=1; k <=(nlstate+ndeath); k++){
                   6572:       if (k != i) {
                   6573:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6574:         if(flatdir[jk]==1){
                   6575:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   6576:         }
                   6577:         for(j=1; j <=ncovmodel; j++){
                   6578:           printf("%12.7f ",p[jk]);
                   6579:           jk++; 
                   6580:         }
                   6581:         printf("\n");
                   6582:       }
                   6583:     }
                   6584:   }
                   6585: /* skipping */
                   6586:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   6587:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   6588:     for(k=1; k <=(nlstate+ndeath); k++){
                   6589:       if (k != i) {
                   6590:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6591:         if(flatdir[jk]==1){
                   6592:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   6593:           for(j=1; j <=ncovmodel;  jk++,j++){
                   6594:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   6595:             /*q[jjk]=p[jk];*/
                   6596:           }
                   6597:         }else{
                   6598:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   6599:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   6600:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   6601:             /*q[jjk]=p[jk];*/
                   6602:           }
                   6603:         }
                   6604:         printf("\n");
                   6605:       }
                   6606:       fflush(stdout);
                   6607:     }
                   6608:   }
                   6609:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6610: #else  /* FLATSUP */
1.359     brouard  6611: /*  powell(p,xi,npar,ftol,&iter,&fret,func);*/
                   6612: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
1.362     brouard  6613:   /* int prin=1; */
                   6614:   /* double h0=0.25; */
                   6615:   /* double macheps; */
                   6616:   /* double fmin; */
1.359     brouard  6617:   macheps=pow(16.0,-13.0);
                   6618: /* #include "praxis.h" */
                   6619:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   6620:    /* praxis ( ftol, h0, npar, prin, p, func ); */
                   6621: /* p1= (p+1); */ /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6622: printf("Praxis Gegenfurtner \n");
                   6623: fprintf(ficlog, "Praxis  Gegenfurtner\n");fflush(ficlog);
                   6624: /* praxis ( ftol, h0, npar, prin, p1, func ); */
                   6625:   /* fmin = praxis(1.e-5,macheps, h, n, prin, x, func); */
1.362     brouard  6626:   ffmin = praxis(ftol,macheps, h0, npar, prin, p, func);
1.359     brouard  6627: printf("End Praxis\n");
1.319     brouard  6628: #endif  /* FLATSUP */
                   6629: 
                   6630: #ifdef LINMINORIGINAL
                   6631: #else
                   6632:       free_ivector(flatdir,1,npar); 
                   6633: #endif  /* LINMINORIGINAL*/
                   6634: #endif /* POWELL */
1.126     brouard  6635: 
1.162     brouard  6636: #ifdef NLOPT
                   6637: #ifdef NEWUOA
                   6638:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   6639: #else
                   6640:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   6641: #endif
                   6642:   lb=vector(0,npar-1);
                   6643:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   6644:   nlopt_set_lower_bounds(opt, lb);
                   6645:   nlopt_set_initial_step1(opt, 0.1);
                   6646:   
                   6647:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6648:   d->function = func;
                   6649:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   6650:   nlopt_set_min_objective(opt, myfunc, d);
                   6651:   nlopt_set_xtol_rel(opt, ftol);
                   6652:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   6653:     printf("nlopt failed! %d\n",creturn); 
                   6654:   }
                   6655:   else {
                   6656:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   6657:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   6658:     iter=1; /* not equal */
                   6659:   }
                   6660:   nlopt_destroy(opt);
                   6661: #endif
1.319     brouard  6662: #ifdef FLATSUP
                   6663:   /* npared = npar -flatd/ncovmodel; */
                   6664:   /* xired= matrix(1,npared,1,npared); */
                   6665:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   6666:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   6667:   /* free_matrix(xire,1,npared,1,npared); */
                   6668: #else  /* FLATSUP */
                   6669: #endif /* FLATSUP */
1.126     brouard  6670:   free_matrix(xi,1,npar,1,npar);
                   6671:   fclose(ficrespow);
1.203     brouard  6672:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   6673:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  6674:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  6675: 
                   6676: }
                   6677: 
                   6678: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  6679: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  6680: {
                   6681:   double  **a,**y,*x,pd;
1.203     brouard  6682:   /* double **hess; */
1.164     brouard  6683:   int i, j;
1.126     brouard  6684:   int *indx;
                   6685: 
                   6686:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  6687:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  6688:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   6689:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   6690:   double gompertz(double p[]);
1.203     brouard  6691:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  6692: 
                   6693:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   6694:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   6695:   for (i=1;i<=npar;i++){
1.203     brouard  6696:     printf("%d-",i);fflush(stdout);
                   6697:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  6698:    
                   6699:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   6700:     
                   6701:     /*  printf(" %f ",p[i]);
                   6702:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   6703:   }
                   6704:   
                   6705:   for (i=1;i<=npar;i++) {
                   6706:     for (j=1;j<=npar;j++)  {
                   6707:       if (j>i) { 
1.203     brouard  6708:        printf(".%d-%d",i,j);fflush(stdout);
                   6709:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   6710:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  6711:        
                   6712:        hess[j][i]=hess[i][j];    
                   6713:        /*printf(" %lf ",hess[i][j]);*/
                   6714:       }
                   6715:     }
                   6716:   }
                   6717:   printf("\n");
                   6718:   fprintf(ficlog,"\n");
                   6719: 
                   6720:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6721:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6722:   
                   6723:   a=matrix(1,npar,1,npar);
                   6724:   y=matrix(1,npar,1,npar);
                   6725:   x=vector(1,npar);
                   6726:   indx=ivector(1,npar);
                   6727:   for (i=1;i<=npar;i++)
                   6728:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   6729:   ludcmp(a,npar,indx,&pd);
                   6730: 
                   6731:   for (j=1;j<=npar;j++) {
                   6732:     for (i=1;i<=npar;i++) x[i]=0;
                   6733:     x[j]=1;
                   6734:     lubksb(a,npar,indx,x);
                   6735:     for (i=1;i<=npar;i++){ 
                   6736:       matcov[i][j]=x[i];
                   6737:     }
                   6738:   }
                   6739: 
                   6740:   printf("\n#Hessian matrix#\n");
                   6741:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   6742:   for (i=1;i<=npar;i++) { 
                   6743:     for (j=1;j<=npar;j++) { 
1.203     brouard  6744:       printf("%.6e ",hess[i][j]);
                   6745:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  6746:     }
                   6747:     printf("\n");
                   6748:     fprintf(ficlog,"\n");
                   6749:   }
                   6750: 
1.203     brouard  6751:   /* printf("\n#Covariance matrix#\n"); */
                   6752:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   6753:   /* for (i=1;i<=npar;i++) {  */
                   6754:   /*   for (j=1;j<=npar;j++) {  */
                   6755:   /*     printf("%.6e ",matcov[i][j]); */
                   6756:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   6757:   /*   } */
                   6758:   /*   printf("\n"); */
                   6759:   /*   fprintf(ficlog,"\n"); */
                   6760:   /* } */
                   6761: 
1.126     brouard  6762:   /* Recompute Inverse */
1.203     brouard  6763:   /* for (i=1;i<=npar;i++) */
                   6764:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   6765:   /* ludcmp(a,npar,indx,&pd); */
                   6766: 
                   6767:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   6768: 
                   6769:   /* for (j=1;j<=npar;j++) { */
                   6770:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   6771:   /*   x[j]=1; */
                   6772:   /*   lubksb(a,npar,indx,x); */
                   6773:   /*   for (i=1;i<=npar;i++){  */
                   6774:   /*     y[i][j]=x[i]; */
                   6775:   /*     printf("%.3e ",y[i][j]); */
                   6776:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   6777:   /*   } */
                   6778:   /*   printf("\n"); */
                   6779:   /*   fprintf(ficlog,"\n"); */
                   6780:   /* } */
                   6781: 
                   6782:   /* Verifying the inverse matrix */
                   6783: #ifdef DEBUGHESS
                   6784:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  6785: 
1.203     brouard  6786:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   6787:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  6788: 
                   6789:   for (j=1;j<=npar;j++) {
                   6790:     for (i=1;i<=npar;i++){ 
1.203     brouard  6791:       printf("%.2f ",y[i][j]);
                   6792:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  6793:     }
                   6794:     printf("\n");
                   6795:     fprintf(ficlog,"\n");
                   6796:   }
1.203     brouard  6797: #endif
1.126     brouard  6798: 
                   6799:   free_matrix(a,1,npar,1,npar);
                   6800:   free_matrix(y,1,npar,1,npar);
                   6801:   free_vector(x,1,npar);
                   6802:   free_ivector(indx,1,npar);
1.203     brouard  6803:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  6804: 
                   6805: 
                   6806: }
                   6807: 
                   6808: /*************** hessian matrix ****************/
                   6809: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  6810: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  6811:   int i;
                   6812:   int l=1, lmax=20;
1.203     brouard  6813:   double k1,k2, res, fx;
1.132     brouard  6814:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  6815:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   6816:   int k=0,kmax=10;
                   6817:   double l1;
                   6818: 
                   6819:   fx=func(x);
                   6820:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  6821:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  6822:     l1=pow(10,l);
                   6823:     delts=delt;
                   6824:     for(k=1 ; k <kmax; k=k+1){
                   6825:       delt = delta*(l1*k);
                   6826:       p2[theta]=x[theta] +delt;
1.145     brouard  6827:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  6828:       p2[theta]=x[theta]-delt;
                   6829:       k2=func(p2)-fx;
                   6830:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  6831:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  6832:       
1.203     brouard  6833: #ifdef DEBUGHESSII
1.126     brouard  6834:       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);
                   6835:       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);
                   6836: #endif
                   6837:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   6838:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   6839:        k=kmax;
                   6840:       }
                   6841:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  6842:        k=kmax; l=lmax*10;
1.126     brouard  6843:       }
                   6844:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   6845:        delts=delt;
                   6846:       }
1.203     brouard  6847:     } /* End loop k */
1.126     brouard  6848:   }
                   6849:   delti[theta]=delts;
                   6850:   return res; 
                   6851:   
                   6852: }
                   6853: 
1.203     brouard  6854: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  6855: {
                   6856:   int i;
1.164     brouard  6857:   int l=1, lmax=20;
1.126     brouard  6858:   double k1,k2,k3,k4,res,fx;
1.132     brouard  6859:   double p2[MAXPARM+1];
1.203     brouard  6860:   int k, kmax=1;
                   6861:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  6862: 
                   6863:   int firstime=0;
1.203     brouard  6864:   
1.126     brouard  6865:   fx=func(x);
1.203     brouard  6866:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  6867:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  6868:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6869:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6870:     k1=func(p2)-fx;
                   6871:   
1.203     brouard  6872:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6873:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6874:     k2=func(p2)-fx;
                   6875:   
1.203     brouard  6876:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6877:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6878:     k3=func(p2)-fx;
                   6879:   
1.203     brouard  6880:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6881:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6882:     k4=func(p2)-fx;
1.203     brouard  6883:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   6884:     if(k1*k2*k3*k4 <0.){
1.208     brouard  6885:       firstime=1;
1.203     brouard  6886:       kmax=kmax+10;
1.208     brouard  6887:     }
                   6888:     if(kmax >=10 || firstime ==1){
1.354     brouard  6889:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  6890:       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);
                   6891:       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  6892:       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);
                   6893:       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);
                   6894:     }
                   6895: #ifdef DEBUGHESSIJ
                   6896:     v1=hess[thetai][thetai];
                   6897:     v2=hess[thetaj][thetaj];
                   6898:     cv12=res;
                   6899:     /* Computing eigen value of Hessian matrix */
                   6900:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6901:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6902:     if ((lc2 <0) || (lc1 <0) ){
                   6903:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6904:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6905:       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);
                   6906:       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);
                   6907:     }
1.126     brouard  6908: #endif
                   6909:   }
                   6910:   return res;
                   6911: }
                   6912: 
1.203     brouard  6913:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   6914: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   6915: /* { */
                   6916: /*   int i; */
                   6917: /*   int l=1, lmax=20; */
                   6918: /*   double k1,k2,k3,k4,res,fx; */
                   6919: /*   double p2[MAXPARM+1]; */
                   6920: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   6921: /*   int k=0,kmax=10; */
                   6922: /*   double l1; */
                   6923:   
                   6924: /*   fx=func(x); */
                   6925: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   6926: /*     l1=pow(10,l); */
                   6927: /*     delts=delt; */
                   6928: /*     for(k=1 ; k <kmax; k=k+1){ */
                   6929: /*       delt = delti*(l1*k); */
                   6930: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   6931: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6932: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6933: /*       k1=func(p2)-fx; */
                   6934:       
                   6935: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6936: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6937: /*       k2=func(p2)-fx; */
                   6938:       
                   6939: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6940: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6941: /*       k3=func(p2)-fx; */
                   6942:       
                   6943: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6944: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6945: /*       k4=func(p2)-fx; */
                   6946: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   6947: /* #ifdef DEBUGHESSIJ */
                   6948: /*       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); */
                   6949: /*       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); */
                   6950: /* #endif */
                   6951: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   6952: /*     k=kmax; */
                   6953: /*       } */
                   6954: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   6955: /*     k=kmax; l=lmax*10; */
                   6956: /*       } */
                   6957: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   6958: /*     delts=delt; */
                   6959: /*       } */
                   6960: /*     } /\* End loop k *\/ */
                   6961: /*   } */
                   6962: /*   delti[theta]=delts; */
                   6963: /*   return res;  */
                   6964: /* } */
                   6965: 
                   6966: 
1.126     brouard  6967: /************** Inverse of matrix **************/
                   6968: void ludcmp(double **a, int n, int *indx, double *d) 
                   6969: { 
                   6970:   int i,imax,j,k; 
                   6971:   double big,dum,sum,temp; 
                   6972:   double *vv; 
                   6973:  
                   6974:   vv=vector(1,n); 
                   6975:   *d=1.0; 
                   6976:   for (i=1;i<=n;i++) { 
                   6977:     big=0.0; 
                   6978:     for (j=1;j<=n;j++) 
                   6979:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  6980:     if (big == 0.0){
                   6981:       printf(" Singular Hessian matrix at row %d:\n",i);
                   6982:       for (j=1;j<=n;j++) {
                   6983:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   6984:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   6985:       }
                   6986:       fflush(ficlog);
                   6987:       fclose(ficlog);
                   6988:       nrerror("Singular matrix in routine ludcmp"); 
                   6989:     }
1.126     brouard  6990:     vv[i]=1.0/big; 
                   6991:   } 
                   6992:   for (j=1;j<=n;j++) { 
                   6993:     for (i=1;i<j;i++) { 
                   6994:       sum=a[i][j]; 
                   6995:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   6996:       a[i][j]=sum; 
                   6997:     } 
                   6998:     big=0.0; 
                   6999:     for (i=j;i<=n;i++) { 
                   7000:       sum=a[i][j]; 
                   7001:       for (k=1;k<j;k++) 
                   7002:        sum -= a[i][k]*a[k][j]; 
                   7003:       a[i][j]=sum; 
                   7004:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   7005:        big=dum; 
                   7006:        imax=i; 
                   7007:       } 
                   7008:     } 
                   7009:     if (j != imax) { 
                   7010:       for (k=1;k<=n;k++) { 
                   7011:        dum=a[imax][k]; 
                   7012:        a[imax][k]=a[j][k]; 
                   7013:        a[j][k]=dum; 
                   7014:       } 
                   7015:       *d = -(*d); 
                   7016:       vv[imax]=vv[j]; 
                   7017:     } 
                   7018:     indx[j]=imax; 
                   7019:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   7020:     if (j != n) { 
                   7021:       dum=1.0/(a[j][j]); 
                   7022:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   7023:     } 
                   7024:   } 
                   7025:   free_vector(vv,1,n);  /* Doesn't work */
                   7026: ;
                   7027: } 
                   7028: 
                   7029: void lubksb(double **a, int n, int *indx, double b[]) 
                   7030: { 
                   7031:   int i,ii=0,ip,j; 
                   7032:   double sum; 
                   7033:  
                   7034:   for (i=1;i<=n;i++) { 
                   7035:     ip=indx[i]; 
                   7036:     sum=b[ip]; 
                   7037:     b[ip]=b[i]; 
                   7038:     if (ii) 
                   7039:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   7040:     else if (sum) ii=i; 
                   7041:     b[i]=sum; 
                   7042:   } 
                   7043:   for (i=n;i>=1;i--) { 
                   7044:     sum=b[i]; 
                   7045:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   7046:     b[i]=sum/a[i][i]; 
                   7047:   } 
                   7048: } 
                   7049: 
                   7050: void pstamp(FILE *fichier)
                   7051: {
1.196     brouard  7052:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  7053: }
                   7054: 
1.297     brouard  7055: void date2dmy(double date,double *day, double *month, double *year){
                   7056:   double yp=0., yp1=0., yp2=0.;
                   7057:   
                   7058:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   7059:                        fractional in yp1 */
                   7060:   *year=yp;
                   7061:   yp2=modf((yp1*12),&yp);
                   7062:   *month=yp;
                   7063:   yp1=modf((yp2*30.5),&yp);
                   7064:   *day=yp;
                   7065:   if(*day==0) *day=1;
                   7066:   if(*month==0) *month=1;
                   7067: }
                   7068: 
1.253     brouard  7069: 
                   7070: 
1.126     brouard  7071: /************ Frequencies ********************/
1.251     brouard  7072: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  7073:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   7074:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  7075: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  7076:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  7077:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  7078:   int iind=0, iage=0;
                   7079:   int mi; /* Effective wave */
                   7080:   int first;
                   7081:   double ***freq; /* Frequencies */
1.268     brouard  7082:   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 */
                   7083:   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  7084:   double *meanq, *stdq, *idq;
1.226     brouard  7085:   double **meanqt;
                   7086:   double *pp, **prop, *posprop, *pospropt;
                   7087:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   7088:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   7089:   double agebegin, ageend;
                   7090:     
                   7091:   pp=vector(1,nlstate);
1.251     brouard  7092:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  7093:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   7094:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   7095:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   7096:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  7097:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  7098:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  7099:   meanqt=matrix(1,lastpass,1,nqtveff);
                   7100:   strcpy(fileresp,"P_");
                   7101:   strcat(fileresp,fileresu);
                   7102:   /*strcat(fileresphtm,fileresu);*/
                   7103:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   7104:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   7105:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   7106:     exit(0);
                   7107:   }
1.240     brouard  7108:   
1.226     brouard  7109:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   7110:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   7111:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7112:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7113:     fflush(ficlog);
                   7114:     exit(70); 
                   7115:   }
                   7116:   else{
                   7117:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  7118: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  7119: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7120:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7121:   }
1.319     brouard  7122:   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  7123:   
1.226     brouard  7124:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   7125:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   7126:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7127:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7128:     fflush(ficlog);
                   7129:     exit(70); 
1.240     brouard  7130:   } else{
1.226     brouard  7131:     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  7132: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  7133: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7134:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7135:   }
1.319     brouard  7136:   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  7137:   
1.253     brouard  7138:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   7139:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  7140:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  7141:   j1=0;
1.126     brouard  7142:   
1.227     brouard  7143:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  7144:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  7145:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  7146:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  7147:   
                   7148:   
1.226     brouard  7149:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   7150:      reference=low_education V1=0,V2=0
                   7151:      med_educ                V1=1 V2=0, 
                   7152:      high_educ               V1=0 V2=1
1.330     brouard  7153:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  7154:   */
1.249     brouard  7155:   dateintsum=0;
                   7156:   k2cpt=0;
                   7157: 
1.253     brouard  7158:   if(cptcoveff == 0 )
1.265     brouard  7159:     nl=1;  /* Constant and age model only */
1.253     brouard  7160:   else
                   7161:     nl=2;
1.265     brouard  7162: 
                   7163:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   7164:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  7165:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  7166:    *     freq[s1][s2][iage] =0.
                   7167:    *     Loop on iind
                   7168:    *       ++freq[s1][s2][iage] weighted
                   7169:    *     end iind
                   7170:    *     if covariate and j!0
                   7171:    *       headers Variable on one line
                   7172:    *     endif cov j!=0
                   7173:    *     header of frequency table by age
                   7174:    *     Loop on age
                   7175:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   7176:    *       pos+=freq[s1][s2][iage] weighted
                   7177:    *       Loop on s1 initial state
                   7178:    *         fprintf(ficresp
                   7179:    *       end s1
                   7180:    *     end age
                   7181:    *     if j!=0 computes starting values
                   7182:    *     end compute starting values
                   7183:    *   end j1
                   7184:    * end nl 
                   7185:    */
1.253     brouard  7186:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   7187:     if(nj==1)
                   7188:       j=0;  /* First pass for the constant */
1.265     brouard  7189:     else{
1.335     brouard  7190:       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  7191:     }
1.251     brouard  7192:     first=1;
1.332     brouard  7193:     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  7194:       posproptt=0.;
1.330     brouard  7195:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  7196:        scanf("%d", i);*/
                   7197:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  7198:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  7199:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  7200:            freq[i][s2][m]=0;
1.251     brouard  7201:       
                   7202:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  7203:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  7204:          prop[i][m]=0;
                   7205:        posprop[i]=0;
                   7206:        pospropt[i]=0;
                   7207:       }
1.283     brouard  7208:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  7209:         idq[z1]=0.;
                   7210:         meanq[z1]=0.;
                   7211:         stdq[z1]=0.;
1.283     brouard  7212:       }
                   7213:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  7214:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  7215:       /*         meanqt[m][z1]=0.; */
                   7216:       /*       } */
                   7217:       /* }       */
1.251     brouard  7218:       /* dateintsum=0; */
                   7219:       /* k2cpt=0; */
                   7220:       
1.265     brouard  7221:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  7222:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   7223:        bool=1;
                   7224:        if(j !=0){
                   7225:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  7226:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   7227:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  7228:                /* if(Tvaraff[z1] ==-20){ */
                   7229:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   7230:                /* }else  if(Tvaraff[z1] ==-10){ */
                   7231:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  7232:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  7233:                /* 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); */
                   7234:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  7235:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  7236:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  7237:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  7238:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  7239:                  /* 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", */
                   7240:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   7241:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  7242:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   7243:                } /* Onlyf fixed */
                   7244:              } /* end z1 */
1.335     brouard  7245:            } /* cptcoveff > 0 */
1.251     brouard  7246:          } /* end any */
                   7247:        }/* end j==0 */
1.265     brouard  7248:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  7249:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  7250:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  7251:            m=mw[mi][iind];
                   7252:            if(j!=0){
                   7253:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  7254:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  7255:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7256:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   7257:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  7258:                    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  7259:                                                                                      value is -1, we don't select. It differs from the 
                   7260:                                                                                      constant and age model which counts them. */
                   7261:                      bool=0; /* not selected */
                   7262:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  7263:                    /* i1=Tvaraff[z1]; */
                   7264:                    /* i2=TnsdVar[i1]; */
                   7265:                    /* i3=nbcode[i1][i2]; */
                   7266:                    /* i4=covar[i1][iind]; */
                   7267:                    /* if(i4 != i3){ */
                   7268:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  7269:                      bool=0;
                   7270:                    }
                   7271:                  }
                   7272:                }
                   7273:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   7274:            } /* end j==0 */
                   7275:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  7276:            if(bool==1){ /*Selected */
1.251     brouard  7277:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   7278:                 and mw[mi+1][iind]. dh depends on stepm. */
                   7279:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   7280:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   7281:              if(m >=firstpass && m <=lastpass){
                   7282:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   7283:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   7284:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   7285:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   7286:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   7287:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   7288:                if (m<lastpass) {
                   7289:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   7290:                  /*   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]); */
                   7291:                  if(s[m][iind]==-1)
                   7292:                    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.));
                   7293:                  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  7294:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   7295:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  7296:                      idq[z1]=idq[z1]+weight[iind];
                   7297:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   7298:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   7299:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  7300:                    }
1.284     brouard  7301:                  }
1.251     brouard  7302:                  /* if((int)agev[m][iind] == 55) */
                   7303:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   7304:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   7305:                  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  7306:                }
1.251     brouard  7307:              } /* end if between passes */  
                   7308:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   7309:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   7310:                k2cpt++;
                   7311:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  7312:              }
1.251     brouard  7313:            }else{
                   7314:              bool=1;
                   7315:            }/* end bool 2 */
                   7316:          } /* end m */
1.284     brouard  7317:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   7318:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   7319:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   7320:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   7321:          /* } */
1.251     brouard  7322:        } /* end bool */
                   7323:       } /* end iind = 1 to imx */
1.319     brouard  7324:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  7325:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   7326:       
                   7327:       
                   7328:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  7329:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  7330:         pstamp(ficresp);
1.335     brouard  7331:       if  (cptcoveff>0 && j!=0){
1.265     brouard  7332:         pstamp(ficresp);
1.251     brouard  7333:        printf( "\n#********** Variable "); 
                   7334:        fprintf(ficresp, "\n#********** Variable "); 
                   7335:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   7336:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   7337:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  7338:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  7339:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  7340:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7341:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7342:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7343:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7344:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  7345:          }else{
1.330     brouard  7346:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7347:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7348:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7349:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7350:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  7351:          }
                   7352:        }
                   7353:        printf( "**********\n#");
                   7354:        fprintf(ficresp, "**********\n#");
                   7355:        fprintf(ficresphtm, "**********</h3>\n");
                   7356:        fprintf(ficresphtmfr, "**********</h3>\n");
                   7357:        fprintf(ficlog, "**********\n");
                   7358:       }
1.284     brouard  7359:       /*
                   7360:        Printing means of quantitative variables if any
                   7361:       */
                   7362:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  7363:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  7364:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  7365:        if(weightopt==1){
                   7366:          printf(" Weighted mean and standard deviation of");
                   7367:          fprintf(ficlog," Weighted mean and standard deviation of");
                   7368:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   7369:        }
1.311     brouard  7370:        /* mu = \frac{w x}{\sum w}
                   7371:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   7372:        */
                   7373:        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]));
                   7374:        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]));
                   7375:        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  7376:       }
                   7377:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   7378:       /*       for(m=1;m<=lastpass;m++){ */
                   7379:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   7380:       /*   } */
                   7381:       /* } */
1.283     brouard  7382: 
1.251     brouard  7383:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  7384:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  7385:         fprintf(ficresp, " Age");
1.335     brouard  7386:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   7387:          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]]);
                   7388:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7389:        }
1.251     brouard  7390:       for(i=1; i<=nlstate;i++) {
1.335     brouard  7391:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  7392:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   7393:       }
1.335     brouard  7394:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  7395:       fprintf(ficresphtm, "\n");
                   7396:       
                   7397:       /* Header of frequency table by age */
                   7398:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   7399:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  7400:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  7401:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7402:          if(s2!=0 && m!=0)
                   7403:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  7404:        }
1.226     brouard  7405:       }
1.251     brouard  7406:       fprintf(ficresphtmfr, "\n");
                   7407:     
                   7408:       /* For each age */
                   7409:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   7410:        fprintf(ficresphtm,"<tr>");
                   7411:        if(iage==iagemax+1){
                   7412:          fprintf(ficlog,"1");
                   7413:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   7414:        }else if(iage==iagemax+2){
                   7415:          fprintf(ficlog,"0");
                   7416:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   7417:        }else if(iage==iagemax+3){
                   7418:          fprintf(ficlog,"Total");
                   7419:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   7420:        }else{
1.240     brouard  7421:          if(first==1){
1.251     brouard  7422:            first=0;
                   7423:            printf("See log file for details...\n");
                   7424:          }
                   7425:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   7426:          fprintf(ficlog,"Age %d", iage);
                   7427:        }
1.265     brouard  7428:        for(s1=1; s1 <=nlstate ; s1++){
                   7429:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   7430:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  7431:        }
1.265     brouard  7432:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7433:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  7434:            pos += freq[s1][m][iage];
                   7435:          if(pp[s1]>=1.e-10){
1.251     brouard  7436:            if(first==1){
1.265     brouard  7437:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7438:            }
1.265     brouard  7439:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7440:          }else{
                   7441:            if(first==1)
1.265     brouard  7442:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   7443:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  7444:          }
                   7445:        }
                   7446:       
1.265     brouard  7447:        for(s1=1; s1 <=nlstate ; s1++){ 
                   7448:          /* posprop[s1]=0; */
                   7449:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   7450:            pp[s1] += freq[s1][m][iage];
                   7451:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   7452:       
                   7453:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   7454:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   7455:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7456:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7457:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7458:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7459:        }
                   7460:        
                   7461:        /* Writing ficresp */
1.335     brouard  7462:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7463:           if( iage <= iagemax){
                   7464:            fprintf(ficresp," %d",iage);
                   7465:           }
                   7466:         }else if( nj==2){
                   7467:           if( iage <= iagemax){
                   7468:            fprintf(ficresp," %d",iage);
1.335     brouard  7469:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  7470:           }
1.240     brouard  7471:        }
1.265     brouard  7472:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  7473:          if(pos>=1.e-5){
1.251     brouard  7474:            if(first==1)
1.265     brouard  7475:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   7476:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  7477:          }else{
                   7478:            if(first==1)
1.265     brouard  7479:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   7480:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  7481:          }
                   7482:          if( iage <= iagemax){
                   7483:            if(pos>=1.e-5){
1.335     brouard  7484:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7485:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7486:               }else if( nj==2){
                   7487:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7488:               }
                   7489:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7490:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   7491:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   7492:            } else{
1.335     brouard  7493:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  7494:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  7495:            }
1.240     brouard  7496:          }
1.265     brouard  7497:          pospropt[s1] +=posprop[s1];
                   7498:        } /* end loop s1 */
1.251     brouard  7499:        /* pospropt=0.; */
1.265     brouard  7500:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  7501:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7502:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  7503:              if(first==1){
1.265     brouard  7504:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7505:              }
1.265     brouard  7506:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   7507:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7508:            }
1.265     brouard  7509:            if(s1!=0 && m!=0)
                   7510:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  7511:          }
1.265     brouard  7512:        } /* end loop s1 */
1.251     brouard  7513:        posproptt=0.; 
1.265     brouard  7514:        for(s1=1; s1 <=nlstate; s1++){
                   7515:          posproptt += pospropt[s1];
1.251     brouard  7516:        }
                   7517:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  7518:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  7519:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  7520:          if(iage <= iagemax)
                   7521:            fprintf(ficresp,"\n");
1.240     brouard  7522:        }
1.251     brouard  7523:        if(first==1)
                   7524:          printf("Others in log...\n");
                   7525:        fprintf(ficlog,"\n");
                   7526:       } /* end loop age iage */
1.265     brouard  7527:       
1.251     brouard  7528:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  7529:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7530:        if(posproptt < 1.e-5){
1.265     brouard  7531:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  7532:        }else{
1.265     brouard  7533:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  7534:        }
1.226     brouard  7535:       }
1.251     brouard  7536:       fprintf(ficresphtm,"</tr>\n");
                   7537:       fprintf(ficresphtm,"</table>\n");
                   7538:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  7539:       if(posproptt < 1.e-5){
1.251     brouard  7540:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   7541:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  7542:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   7543:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  7544:        invalidvarcomb[j1]=1;
1.226     brouard  7545:       }else{
1.338     brouard  7546:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  7547:        invalidvarcomb[j1]=0;
1.226     brouard  7548:       }
1.251     brouard  7549:       fprintf(ficresphtmfr,"</table>\n");
                   7550:       fprintf(ficlog,"\n");
                   7551:       if(j!=0){
                   7552:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  7553:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7554:          for(k=1; k <=(nlstate+ndeath); k++){
                   7555:            if (k != i) {
1.265     brouard  7556:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  7557:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  7558:                  if(j1==1){ /* All dummy covariates to zero */
                   7559:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   7560:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  7561:                    printf("%d%d ",i,k);
                   7562:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7563:                    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]));
                   7564:                    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]));
                   7565:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  7566:                  }
1.253     brouard  7567:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   7568:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   7569:                    x[iage]= (double)iage;
                   7570:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  7571:                    /* 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  7572:                  }
1.268     brouard  7573:                  /* Some are not finite, but linreg will ignore these ages */
                   7574:                  no=0;
1.253     brouard  7575:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  7576:                  pstart[s1]=b;
                   7577:                  pstart[s1-1]=a;
1.252     brouard  7578:                }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 */ 
                   7579:                  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]);
                   7580:                  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  7581:                  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  7582:                  printf("%d%d ",i,k);
                   7583:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7584:                  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  7585:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   7586:                  ;
                   7587:                }
                   7588:                /* printf("%12.7f )", param[i][jj][k]); */
                   7589:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7590:                s1++; 
1.251     brouard  7591:              } /* end jj */
                   7592:            } /* end k!= i */
                   7593:          } /* end k */
1.265     brouard  7594:        } /* end i, s1 */
1.251     brouard  7595:       } /* end j !=0 */
                   7596:     } /* end selected combination of covariate j1 */
                   7597:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   7598:       printf("#Freqsummary: Starting values for the constants:\n");
                   7599:       fprintf(ficlog,"\n");
1.265     brouard  7600:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7601:        for(k=1; k <=(nlstate+ndeath); k++){
                   7602:          if (k != i) {
                   7603:            printf("%d%d ",i,k);
                   7604:            fprintf(ficlog,"%d%d ",i,k);
                   7605:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  7606:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  7607:              if(jj==1){ /* Age has to be done */
1.265     brouard  7608:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   7609:                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]));
                   7610:                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  7611:              }
                   7612:              /* printf("%12.7f )", param[i][jj][k]); */
                   7613:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7614:              s1++; 
1.250     brouard  7615:            }
1.251     brouard  7616:            printf("\n");
                   7617:            fprintf(ficlog,"\n");
1.250     brouard  7618:          }
                   7619:        }
1.284     brouard  7620:       } /* end of state i */
1.251     brouard  7621:       printf("#Freqsummary\n");
                   7622:       fprintf(ficlog,"\n");
1.265     brouard  7623:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   7624:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   7625:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   7626:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7627:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7628:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   7629:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   7630:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  7631:          /* } */
                   7632:        }
1.265     brouard  7633:       } /* end loop s1 */
1.251     brouard  7634:       
                   7635:       printf("\n");
                   7636:       fprintf(ficlog,"\n");
                   7637:     } /* end j=0 */
1.249     brouard  7638:   } /* end j */
1.252     brouard  7639: 
1.253     brouard  7640:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  7641:     for(i=1, jk=1; i <=nlstate; i++){
                   7642:       for(j=1; j <=nlstate+ndeath; j++){
                   7643:        if(j!=i){
                   7644:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7645:          printf("%1d%1d",i,j);
                   7646:          fprintf(ficparo,"%1d%1d",i,j);
                   7647:          for(k=1; k<=ncovmodel;k++){
                   7648:            /*    printf(" %lf",param[i][j][k]); */
                   7649:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   7650:            p[jk]=pstart[jk];
                   7651:            printf(" %f ",pstart[jk]);
                   7652:            fprintf(ficparo," %f ",pstart[jk]);
                   7653:            jk++;
                   7654:          }
                   7655:          printf("\n");
                   7656:          fprintf(ficparo,"\n");
                   7657:        }
                   7658:       }
                   7659:     }
                   7660:   } /* end mle=-2 */
1.226     brouard  7661:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  7662:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  7663:   
1.226     brouard  7664:   fclose(ficresp);
                   7665:   fclose(ficresphtm);
                   7666:   fclose(ficresphtmfr);
1.283     brouard  7667:   free_vector(idq,1,nqfveff);
1.226     brouard  7668:   free_vector(meanq,1,nqfveff);
1.284     brouard  7669:   free_vector(stdq,1,nqfveff);
1.226     brouard  7670:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  7671:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   7672:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  7673:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7674:   free_vector(pospropt,1,nlstate);
                   7675:   free_vector(posprop,1,nlstate);
1.251     brouard  7676:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7677:   free_vector(pp,1,nlstate);
                   7678:   /* End of freqsummary */
                   7679: }
1.126     brouard  7680: 
1.268     brouard  7681: /* Simple linear regression */
                   7682: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   7683: 
                   7684:   /* y=a+bx regression */
                   7685:   double   sumx = 0.0;                        /* sum of x                      */
                   7686:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   7687:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   7688:   double   sumy = 0.0;                        /* sum of y                      */
                   7689:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   7690:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   7691:   double yhat;
                   7692:   
                   7693:   double denom=0;
                   7694:   int i;
                   7695:   int ne=*no;
                   7696:   
                   7697:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7698:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7699:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7700:       continue;
                   7701:     }
                   7702:     ne=ne+1;
                   7703:     sumx  += x[i];       
                   7704:     sumx2 += x[i]*x[i];  
                   7705:     sumxy += x[i] * y[i];
                   7706:     sumy  += y[i];      
                   7707:     sumy2 += y[i]*y[i]; 
                   7708:     denom = (ne * sumx2 - sumx*sumx);
                   7709:     /* 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); */
                   7710:   } 
                   7711:   
                   7712:   denom = (ne * sumx2 - sumx*sumx);
                   7713:   if (denom == 0) {
                   7714:     // vertical, slope m is infinity
                   7715:     *b = INFINITY;
                   7716:     *a = 0;
                   7717:     if (r) *r = 0;
                   7718:     return 1;
                   7719:   }
                   7720:   
                   7721:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   7722:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   7723:   if (r!=NULL) {
                   7724:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   7725:       sqrt((sumx2 - sumx*sumx/ne) *
                   7726:           (sumy2 - sumy*sumy/ne));
                   7727:   }
                   7728:   *no=ne;
                   7729:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7730:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7731:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7732:       continue;
                   7733:     }
                   7734:     ne=ne+1;
                   7735:     yhat = y[i] - *a -*b* x[i];
                   7736:     sume2  += yhat * yhat ;       
                   7737:     
                   7738:     denom = (ne * sumx2 - sumx*sumx);
                   7739:     /* 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); */
                   7740:   } 
                   7741:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   7742:   *sa= *sb * sqrt(sumx2/ne);
                   7743:   
                   7744:   return 0; 
                   7745: }
                   7746: 
1.126     brouard  7747: /************ Prevalence ********************/
1.227     brouard  7748: 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)
                   7749: {  
                   7750:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7751:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7752:      We still use firstpass and lastpass as another selection.
                   7753:   */
1.126     brouard  7754:  
1.227     brouard  7755:   int i, m, jk, j1, bool, z1,j, iv;
                   7756:   int mi; /* Effective wave */
                   7757:   int iage;
1.359     brouard  7758:   double agebegin; /*, ageend;*/
1.227     brouard  7759: 
                   7760:   double **prop;
                   7761:   double posprop; 
                   7762:   double  y2; /* in fractional years */
                   7763:   int iagemin, iagemax;
                   7764:   int first; /** to stop verbosity which is redirected to log file */
                   7765: 
                   7766:   iagemin= (int) agemin;
                   7767:   iagemax= (int) agemax;
                   7768:   /*pp=vector(1,nlstate);*/
1.251     brouard  7769:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  7770:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   7771:   j1=0;
1.222     brouard  7772:   
1.227     brouard  7773:   /*j=cptcoveff;*/
                   7774:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  7775:   
1.288     brouard  7776:   first=0;
1.335     brouard  7777:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  7778:     for (i=1; i<=nlstate; i++)  
1.251     brouard  7779:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  7780:        prop[i][iage]=0.0;
                   7781:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   7782:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   7783:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   7784:     
                   7785:     for (i=1; i<=imx; i++) { /* Each individual */
                   7786:       bool=1;
                   7787:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   7788:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   7789:        m=mw[mi][i];
                   7790:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   7791:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   7792:        for (z1=1; z1<=cptcoveff; z1++){
                   7793:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7794:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  7795:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  7796:              bool=0;
                   7797:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  7798:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  7799:              bool=0;
                   7800:            }
                   7801:        }
                   7802:        if(bool==1){ /* Otherwise we skip that wave/person */
                   7803:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   7804:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   7805:          if(m >=firstpass && m <=lastpass){
                   7806:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   7807:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   7808:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   7809:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  7810:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  7811:                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); 
                   7812:                exit(1);
                   7813:              }
                   7814:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   7815:                /*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]]);*/
                   7816:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   7817:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   7818:              } /* end valid statuses */ 
                   7819:            } /* end selection of dates */
                   7820:          } /* end selection of waves */
                   7821:        } /* end bool */
                   7822:       } /* end wave */
                   7823:     } /* end individual */
                   7824:     for(i=iagemin; i <= iagemax+3; i++){  
                   7825:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   7826:        posprop += prop[jk][i]; 
                   7827:       } 
                   7828:       
                   7829:       for(jk=1; jk <=nlstate ; jk++){      
                   7830:        if( i <=  iagemax){ 
                   7831:          if(posprop>=1.e-5){ 
                   7832:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   7833:          } else{
1.288     brouard  7834:            if(!first){
                   7835:              first=1;
1.266     brouard  7836:              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]);
                   7837:            }else{
1.288     brouard  7838:              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  7839:            }
                   7840:          }
                   7841:        } 
                   7842:       }/* end jk */ 
                   7843:     }/* end i */ 
1.222     brouard  7844:      /*} *//* end i1 */
1.227     brouard  7845:   } /* end j1 */
1.222     brouard  7846:   
1.227     brouard  7847:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   7848:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  7849:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  7850: }  /* End of prevalence */
1.126     brouard  7851: 
                   7852: /************* Waves Concatenation ***************/
                   7853: 
                   7854: 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)
                   7855: {
1.298     brouard  7856:   /* 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  7857:      Death is a valid wave (if date is known).
                   7858:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   7859:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  7860:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  7861:   */
1.126     brouard  7862: 
1.224     brouard  7863:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  7864:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   7865:      double sum=0., jmean=0.;*/
1.224     brouard  7866:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  7867:   int j, k=0,jk, ju, jl;
                   7868:   double sum=0.;
                   7869:   first=0;
1.214     brouard  7870:   firstwo=0;
1.217     brouard  7871:   firsthree=0;
1.218     brouard  7872:   firstfour=0;
1.164     brouard  7873:   jmin=100000;
1.126     brouard  7874:   jmax=-1;
                   7875:   jmean=0.;
1.224     brouard  7876: 
                   7877: /* Treating live states */
1.214     brouard  7878:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  7879:     mi=0;  /* First valid wave */
1.227     brouard  7880:     mli=0; /* Last valid wave */
1.309     brouard  7881:     m=firstpass;  /* Loop on waves */
                   7882:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  7883:       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 */
                   7884:        mli=m-1;/* mw[++mi][i]=m-1; */
                   7885:       }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  7886:        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  7887:        mli=m;
1.224     brouard  7888:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   7889:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  7890:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  7891:       }
1.309     brouard  7892:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  7893: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  7894:        break;
1.224     brouard  7895: #else
1.317     brouard  7896:        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  7897:          if(firsthree == 0){
1.302     brouard  7898:            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  7899:            firsthree=1;
1.317     brouard  7900:          }else if(firsthree >=1 && firsthree < 10){
                   7901:            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);
                   7902:            firsthree++;
                   7903:          }else if(firsthree == 10){
                   7904:            printf("Information, too many Information flags: no more reported to log either\n");
                   7905:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   7906:            firsthree++;
                   7907:          }else{
                   7908:            firsthree++;
1.227     brouard  7909:          }
1.309     brouard  7910:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  7911:          mli=m;
                   7912:        }
                   7913:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   7914:          nbwarn++;
1.309     brouard  7915:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  7916:            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);
                   7917:            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);
                   7918:          }
                   7919:          break;
                   7920:        }
                   7921:        break;
1.224     brouard  7922: #endif
1.227     brouard  7923:       }/* End m >= lastpass */
1.126     brouard  7924:     }/* end while */
1.224     brouard  7925: 
1.227     brouard  7926:     /* 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  7927:     /* After last pass */
1.224     brouard  7928: /* Treating death states */
1.214     brouard  7929:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  7930:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   7931:       /* } */
1.126     brouard  7932:       mi++;    /* Death is another wave */
                   7933:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  7934:       /* Only death is a correct wave */
1.126     brouard  7935:       mw[mi][i]=m;
1.257     brouard  7936:     } /* else not in a death state */
1.224     brouard  7937: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  7938:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  7939:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  7940:        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  7941:          nbwarn++;
                   7942:          if(firstfiv==0){
1.309     brouard  7943:            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  7944:            firstfiv=1;
                   7945:          }else{
1.309     brouard  7946:            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  7947:          }
1.309     brouard  7948:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   7949:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  7950:          nberr++;
                   7951:          if(firstwo==0){
1.309     brouard  7952:            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  7953:            firstwo=1;
                   7954:          }
1.309     brouard  7955:          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  7956:        }
1.257     brouard  7957:       }else{ /* if date of interview is unknown */
1.227     brouard  7958:        /* death is known but not confirmed by death status at any wave */
                   7959:        if(firstfour==0){
1.309     brouard  7960:          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  7961:          firstfour=1;
                   7962:        }
1.309     brouard  7963:        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  7964:       }
1.224     brouard  7965:     } /* end if date of death is known */
                   7966: #endif
1.309     brouard  7967:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   7968:     /* wav[i]=mw[mi][i];   */
1.126     brouard  7969:     if(mi==0){
                   7970:       nbwarn++;
                   7971:       if(first==0){
1.227     brouard  7972:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   7973:        first=1;
1.126     brouard  7974:       }
                   7975:       if(first==1){
1.227     brouard  7976:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  7977:       }
                   7978:     } /* end mi==0 */
                   7979:   } /* End individuals */
1.214     brouard  7980:   /* wav and mw are no more changed */
1.223     brouard  7981:        
1.317     brouard  7982:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7983:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7984: 
                   7985: 
1.126     brouard  7986:   for(i=1; i<=imx; i++){
                   7987:     for(mi=1; mi<wav[i];mi++){
                   7988:       if (stepm <=0)
1.227     brouard  7989:        dh[mi][i]=1;
1.126     brouard  7990:       else{
1.260     brouard  7991:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  7992:          if (agedc[i] < 2*AGESUP) {
                   7993:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   7994:            if(j==0) j=1;  /* Survives at least one month after exam */
                   7995:            else if(j<0){
                   7996:              nberr++;
1.359     brouard  7997:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around line %d) who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
1.227     brouard  7998:              j=1; /* Temporary Dangerous patch */
                   7999:              printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
1.359     brouard  8000:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around line %d) who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
1.227     brouard  8001:              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);
                   8002:            }
                   8003:            k=k+1;
                   8004:            if (j >= jmax){
                   8005:              jmax=j;
                   8006:              ijmax=i;
                   8007:            }
                   8008:            if (j <= jmin){
                   8009:              jmin=j;
                   8010:              ijmin=i;
                   8011:            }
                   8012:            sum=sum+j;
                   8013:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   8014:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   8015:          }
                   8016:        }
                   8017:        else{
                   8018:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  8019: /*       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  8020:                                        
1.227     brouard  8021:          k=k+1;
                   8022:          if (j >= jmax) {
                   8023:            jmax=j;
                   8024:            ijmax=i;
                   8025:          }
                   8026:          else if (j <= jmin){
                   8027:            jmin=j;
                   8028:            ijmin=i;
                   8029:          }
                   8030:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   8031:          /*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]);*/
                   8032:          if(j<0){
                   8033:            nberr++;
1.359     brouard  8034:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld (around line %d) who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   8035:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld (around line %d) who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
1.227     brouard  8036:          }
                   8037:          sum=sum+j;
                   8038:        }
                   8039:        jk= j/stepm;
                   8040:        jl= j -jk*stepm;
                   8041:        ju= j -(jk+1)*stepm;
                   8042:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   8043:          if(jl==0){
                   8044:            dh[mi][i]=jk;
                   8045:            bh[mi][i]=0;
                   8046:          }else{ /* We want a negative bias in order to only have interpolation ie
                   8047:                  * to avoid the price of an extra matrix product in likelihood */
                   8048:            dh[mi][i]=jk+1;
                   8049:            bh[mi][i]=ju;
                   8050:          }
                   8051:        }else{
                   8052:          if(jl <= -ju){
                   8053:            dh[mi][i]=jk;
                   8054:            bh[mi][i]=jl;       /* bias is positive if real duration
                   8055:                                 * is higher than the multiple of stepm and negative otherwise.
                   8056:                                 */
                   8057:          }
                   8058:          else{
                   8059:            dh[mi][i]=jk+1;
                   8060:            bh[mi][i]=ju;
                   8061:          }
                   8062:          if(dh[mi][i]==0){
                   8063:            dh[mi][i]=1; /* At least one step */
                   8064:            bh[mi][i]=ju; /* At least one step */
                   8065:            /*  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);*/
                   8066:          }
                   8067:        } /* end if mle */
1.126     brouard  8068:       }
                   8069:     } /* end wave */
                   8070:   }
                   8071:   jmean=sum/k;
                   8072:   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  8073:   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  8074: }
1.126     brouard  8075: 
                   8076: /*********** Tricode ****************************/
1.220     brouard  8077:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  8078:  {
                   8079:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   8080:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   8081:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   8082:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   8083:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   8084:     */
1.130     brouard  8085: 
1.242     brouard  8086:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   8087:    int modmaxcovj=0; /* Modality max of covariates j */
                   8088:    int cptcode=0; /* Modality max of covariates j */
                   8089:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  8090: 
                   8091: 
1.242     brouard  8092:    /* cptcoveff=0;  */
                   8093:    /* *cptcov=0; */
1.126     brouard  8094:  
1.242     brouard  8095:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  8096:    for (k=1; k <= maxncov; k++)
                   8097:      for(j=1; j<=2; j++)
                   8098:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  8099: 
1.242     brouard  8100:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  8101:    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  8102:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  8103:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  8104:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  8105:        switch(Fixed[k]) {
                   8106:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  8107:         modmaxcovj=0;
                   8108:         modmincovj=0;
1.242     brouard  8109:         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  8110:           /* 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  8111:           ij=(int)(covar[Tvar[k]][i]);
                   8112:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   8113:            * If product of Vn*Vm, still boolean *:
                   8114:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   8115:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   8116:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   8117:              modality of the nth covariate of individual i. */
                   8118:           if (ij > modmaxcovj)
                   8119:             modmaxcovj=ij; 
                   8120:           else if (ij < modmincovj) 
                   8121:             modmincovj=ij; 
1.287     brouard  8122:           if (ij <0 || ij >1 ){
1.311     brouard  8123:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8124:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8125:             fflush(ficlog);
                   8126:             exit(1);
1.287     brouard  8127:           }
                   8128:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  8129:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   8130:             exit(1);
                   8131:           }else
                   8132:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   8133:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   8134:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   8135:           /* getting the maximum value of the modality of the covariate
                   8136:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   8137:              female ies 1, then modmaxcovj=1.
                   8138:           */
                   8139:         } /* end for loop on individuals i */
                   8140:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8141:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8142:         cptcode=modmaxcovj;
                   8143:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   8144:         /*for (i=0; i<=cptcode; i++) {*/
                   8145:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   8146:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8147:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8148:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   8149:             if( j != -1){
                   8150:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   8151:                                  covariate for which somebody answered excluding 
                   8152:                                  undefined. Usually 2: 0 and 1. */
                   8153:             }
                   8154:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   8155:                                     covariate for which somebody answered including 
                   8156:                                     undefined. Usually 3: -1, 0 and 1. */
                   8157:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   8158:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   8159:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  8160:                        
1.242     brouard  8161:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   8162:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   8163:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   8164:         /* modmincovj=3; modmaxcovj = 7; */
                   8165:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   8166:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   8167:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   8168:         /* nbcode[Tvar[j]][ij]=k; */
                   8169:         /* nbcode[Tvar[j]][1]=0; */
                   8170:         /* nbcode[Tvar[j]][2]=1; */
                   8171:         /* nbcode[Tvar[j]][3]=2; */
                   8172:         /* To be continued (not working yet). */
                   8173:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  8174: 
                   8175:         /* 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*/
                   8176:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   8177:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   8178:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   8179:         /*, could be restored in the future */
                   8180:         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  8181:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   8182:             break;
                   8183:           }
                   8184:           ij++;
1.287     brouard  8185:           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  8186:           cptcode = ij; /* New max modality for covar j */
                   8187:         } /* end of loop on modality i=-1 to 1 or more */
                   8188:         break;
                   8189:        case 1: /* Testing on varying covariate, could be simple and
                   8190:                * should look at waves or product of fixed *
                   8191:                * varying. No time to test -1, assuming 0 and 1 only */
                   8192:         ij=0;
                   8193:         for(i=0; i<=1;i++){
                   8194:           nbcode[Tvar[k]][++ij]=i;
                   8195:         }
                   8196:         break;
                   8197:        default:
                   8198:         break;
                   8199:        } /* end switch */
                   8200:      } /* end dummy test */
1.349     brouard  8201:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  8202:        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  8203:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   8204:           printf("Error k=%d \n",k);
                   8205:           exit(1);
                   8206:         }
1.311     brouard  8207:         if(isnan(covar[Tvar[k]][i])){
                   8208:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8209:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8210:           fflush(ficlog);
                   8211:           exit(1);
                   8212:          }
                   8213:        }
1.335     brouard  8214:      } /* end Quanti */
1.287     brouard  8215:    } /* 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  8216:   
                   8217:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   8218:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   8219:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   8220:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   8221:      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 */ 
                   8222:      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 */
                   8223:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   8224:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   8225:   
                   8226:    ij=0;
                   8227:    /* 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  8228:    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 */
                   8229:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  8230:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   8231:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  8232:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   8233:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   8234:        /* 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  8235:        /* If product not in single variable we don't print results */
                   8236:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  8237:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   8238:        /* k=       1    2   3     4       5       6      7       8        9  */
                   8239:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   8240:        /* ij            1    2                                            3  */  
                   8241:        /* Tvaraff[ij]=  4    3                                            1  */
                   8242:        /* Tmodelind[ij]=2    3                                            9  */
                   8243:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  8244:        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*/
                   8245:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   8246:        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 */
                   8247:        if(Fixed[k]!=0)
                   8248:         anyvaryingduminmodel=1;
                   8249:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   8250:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8251:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   8252:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   8253:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   8254:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8255:      } 
                   8256:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   8257:    /* ij--; */
                   8258:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  8259:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  8260:                * because they can be excluded from the model and real
                   8261:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   8262:    for(j=ij+1; j<= cptcovt; j++){
                   8263:      Tvaraff[j]=0;
                   8264:      Tmodelind[j]=0;
                   8265:    }
                   8266:    for(j=ntveff+1; j<= cptcovt; j++){
                   8267:      TmodelInvind[j]=0;
                   8268:    }
                   8269:    /* To be sorted */
                   8270:    ;
                   8271:  }
1.126     brouard  8272: 
1.145     brouard  8273: 
1.126     brouard  8274: /*********** Health Expectancies ****************/
                   8275: 
1.235     brouard  8276:  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  8277: 
                   8278: {
                   8279:   /* Health expectancies, no variances */
1.329     brouard  8280:   /* cij is the combination in the list of combination of dummy covariates */
                   8281:   /* strstart is a string of time at start of computing */
1.164     brouard  8282:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  8283:   int nhstepma, nstepma; /* Decreasing with age */
                   8284:   double age, agelim, hf;
                   8285:   double ***p3mat;
                   8286:   double eip;
                   8287: 
1.238     brouard  8288:   /* pstamp(ficreseij); */
1.126     brouard  8289:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   8290:   fprintf(ficreseij,"# Age");
                   8291:   for(i=1; i<=nlstate;i++){
                   8292:     for(j=1; j<=nlstate;j++){
                   8293:       fprintf(ficreseij," e%1d%1d ",i,j);
                   8294:     }
                   8295:     fprintf(ficreseij," e%1d. ",i);
                   8296:   }
                   8297:   fprintf(ficreseij,"\n");
                   8298: 
                   8299:   
                   8300:   if(estepm < stepm){
                   8301:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8302:   }
                   8303:   else  hstepm=estepm;   
                   8304:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8305:    * This is mainly to measure the difference between two models: for example
                   8306:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8307:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8308:    * progression in between and thus overestimating or underestimating according
                   8309:    * to the curvature of the survival function. If, for the same date, we 
                   8310:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8311:    * to compare the new estimate of Life expectancy with the same linear 
                   8312:    * hypothesis. A more precise result, taking into account a more precise
                   8313:    * curvature will be obtained if estepm is as small as stepm. */
                   8314: 
                   8315:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8316:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8317:      nhstepm is the number of hstepm from age to agelim 
                   8318:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  8319:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  8320:      and note for a fixed period like estepm months */
                   8321:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8322:      survival function given by stepm (the optimization length). Unfortunately it
                   8323:      means that if the survival funtion is printed only each two years of age and if
                   8324:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8325:      results. So we changed our mind and took the option of the best precision.
                   8326:   */
                   8327:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8328: 
                   8329:   agelim=AGESUP;
                   8330:   /* If stepm=6 months */
                   8331:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   8332:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   8333:     
                   8334: /* nhstepm age range expressed in number of stepm */
                   8335:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8336:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8337:   /* if (stepm >= YEARM) hstepm=1;*/
                   8338:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8339:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8340: 
                   8341:   for (age=bage; age<=fage; age ++){ 
                   8342:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8343:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8344:     /* if (stepm >= YEARM) hstepm=1;*/
                   8345:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   8346: 
                   8347:     /* If stepm=6 months */
                   8348:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8349:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  8350:     /* 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  8351:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  8352:     
                   8353:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8354:     
                   8355:     printf("%d|",(int)age);fflush(stdout);
                   8356:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8357:     
                   8358:     /* Computing expectancies */
                   8359:     for(i=1; i<=nlstate;i++)
                   8360:       for(j=1; j<=nlstate;j++)
                   8361:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8362:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   8363:          
                   8364:          /* 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]);*/
                   8365: 
                   8366:        }
                   8367: 
                   8368:     fprintf(ficreseij,"%3.0f",age );
                   8369:     for(i=1; i<=nlstate;i++){
                   8370:       eip=0;
                   8371:       for(j=1; j<=nlstate;j++){
                   8372:        eip +=eij[i][j][(int)age];
                   8373:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   8374:       }
                   8375:       fprintf(ficreseij,"%9.4f", eip );
                   8376:     }
                   8377:     fprintf(ficreseij,"\n");
                   8378:     
                   8379:   }
                   8380:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8381:   printf("\n");
                   8382:   fprintf(ficlog,"\n");
                   8383:   
                   8384: }
                   8385: 
1.235     brouard  8386:  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  8387: 
                   8388: {
                   8389:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  8390:      to initial status i, ei. .
1.126     brouard  8391:   */
1.336     brouard  8392:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  8393:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   8394:   int nhstepma, nstepma; /* Decreasing with age */
                   8395:   double age, agelim, hf;
                   8396:   double ***p3matp, ***p3matm, ***varhe;
                   8397:   double **dnewm,**doldm;
                   8398:   double *xp, *xm;
                   8399:   double **gp, **gm;
                   8400:   double ***gradg, ***trgradg;
                   8401:   int theta;
                   8402: 
                   8403:   double eip, vip;
                   8404: 
                   8405:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   8406:   xp=vector(1,npar);
                   8407:   xm=vector(1,npar);
                   8408:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   8409:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   8410:   
                   8411:   pstamp(ficresstdeij);
                   8412:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   8413:   fprintf(ficresstdeij,"# Age");
                   8414:   for(i=1; i<=nlstate;i++){
                   8415:     for(j=1; j<=nlstate;j++)
                   8416:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   8417:     fprintf(ficresstdeij," e%1d. ",i);
                   8418:   }
                   8419:   fprintf(ficresstdeij,"\n");
                   8420: 
                   8421:   pstamp(ficrescveij);
                   8422:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   8423:   fprintf(ficrescveij,"# Age");
                   8424:   for(i=1; i<=nlstate;i++)
                   8425:     for(j=1; j<=nlstate;j++){
                   8426:       cptj= (j-1)*nlstate+i;
                   8427:       for(i2=1; i2<=nlstate;i2++)
                   8428:        for(j2=1; j2<=nlstate;j2++){
                   8429:          cptj2= (j2-1)*nlstate+i2;
                   8430:          if(cptj2 <= cptj)
                   8431:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   8432:        }
                   8433:     }
                   8434:   fprintf(ficrescveij,"\n");
                   8435:   
                   8436:   if(estepm < stepm){
                   8437:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8438:   }
                   8439:   else  hstepm=estepm;   
                   8440:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8441:    * This is mainly to measure the difference between two models: for example
                   8442:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8443:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8444:    * progression in between and thus overestimating or underestimating according
                   8445:    * to the curvature of the survival function. If, for the same date, we 
                   8446:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8447:    * to compare the new estimate of Life expectancy with the same linear 
                   8448:    * hypothesis. A more precise result, taking into account a more precise
                   8449:    * curvature will be obtained if estepm is as small as stepm. */
                   8450: 
                   8451:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8452:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8453:      nhstepm is the number of hstepm from age to agelim 
                   8454:      nstepm is the number of stepm from age to agelin. 
                   8455:      Look at hpijx to understand the reason of that which relies in memory size
                   8456:      and note for a fixed period like estepm months */
                   8457:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8458:      survival function given by stepm (the optimization length). Unfortunately it
                   8459:      means that if the survival funtion is printed only each two years of age and if
                   8460:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8461:      results. So we changed our mind and took the option of the best precision.
                   8462:   */
                   8463:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8464: 
                   8465:   /* If stepm=6 months */
                   8466:   /* nhstepm age range expressed in number of stepm */
                   8467:   agelim=AGESUP;
                   8468:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   8469:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8470:   /* if (stepm >= YEARM) hstepm=1;*/
                   8471:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8472:   
                   8473:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8474:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8475:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   8476:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   8477:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   8478:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   8479: 
                   8480:   for (age=bage; age<=fage; age ++){ 
                   8481:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8482:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8483:     /* if (stepm >= YEARM) hstepm=1;*/
                   8484:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  8485:                
1.126     brouard  8486:     /* If stepm=6 months */
                   8487:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8488:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   8489:     
                   8490:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  8491:                
1.126     brouard  8492:     /* Computing  Variances of health expectancies */
                   8493:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   8494:        decrease memory allocation */
                   8495:     for(theta=1; theta <=npar; theta++){
                   8496:       for(i=1; i<=npar; i++){ 
1.222     brouard  8497:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8498:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  8499:       }
1.235     brouard  8500:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   8501:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  8502:                        
1.126     brouard  8503:       for(j=1; j<= nlstate; j++){
1.222     brouard  8504:        for(i=1; i<=nlstate; i++){
                   8505:          for(h=0; h<=nhstepm-1; h++){
                   8506:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   8507:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   8508:          }
                   8509:        }
1.126     brouard  8510:       }
1.218     brouard  8511:                        
1.126     brouard  8512:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  8513:        for(h=0; h<=nhstepm-1; h++){
                   8514:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   8515:        }
1.126     brouard  8516:     }/* End theta */
                   8517:     
                   8518:     
                   8519:     for(h=0; h<=nhstepm-1; h++)
                   8520:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  8521:        for(theta=1; theta <=npar; theta++)
                   8522:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  8523:     
1.218     brouard  8524:                
1.222     brouard  8525:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  8526:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  8527:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  8528:                
1.222     brouard  8529:     printf("%d|",(int)age);fflush(stdout);
                   8530:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8531:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  8532:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  8533:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   8534:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   8535:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   8536:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   8537:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  8538:       }
                   8539:     }
1.320     brouard  8540:     /* if((int)age ==50){ */
                   8541:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   8542:     /* } */
1.126     brouard  8543:     /* Computing expectancies */
1.235     brouard  8544:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  8545:     for(i=1; i<=nlstate;i++)
                   8546:       for(j=1; j<=nlstate;j++)
1.222     brouard  8547:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8548:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  8549:                                        
1.222     brouard  8550:          /* 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  8551:                                        
1.222     brouard  8552:        }
1.269     brouard  8553: 
                   8554:     /* Standard deviation of expectancies ij */                
1.126     brouard  8555:     fprintf(ficresstdeij,"%3.0f",age );
                   8556:     for(i=1; i<=nlstate;i++){
                   8557:       eip=0.;
                   8558:       vip=0.;
                   8559:       for(j=1; j<=nlstate;j++){
1.222     brouard  8560:        eip += eij[i][j][(int)age];
                   8561:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   8562:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   8563:        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  8564:       }
                   8565:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   8566:     }
                   8567:     fprintf(ficresstdeij,"\n");
1.218     brouard  8568:                
1.269     brouard  8569:     /* Variance of expectancies ij */          
1.126     brouard  8570:     fprintf(ficrescveij,"%3.0f",age );
                   8571:     for(i=1; i<=nlstate;i++)
                   8572:       for(j=1; j<=nlstate;j++){
1.222     brouard  8573:        cptj= (j-1)*nlstate+i;
                   8574:        for(i2=1; i2<=nlstate;i2++)
                   8575:          for(j2=1; j2<=nlstate;j2++){
                   8576:            cptj2= (j2-1)*nlstate+i2;
                   8577:            if(cptj2 <= cptj)
                   8578:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   8579:          }
1.126     brouard  8580:       }
                   8581:     fprintf(ficrescveij,"\n");
1.218     brouard  8582:                
1.126     brouard  8583:   }
                   8584:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   8585:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   8586:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   8587:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   8588:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8589:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8590:   printf("\n");
                   8591:   fprintf(ficlog,"\n");
1.218     brouard  8592:        
1.126     brouard  8593:   free_vector(xm,1,npar);
                   8594:   free_vector(xp,1,npar);
                   8595:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   8596:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   8597:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   8598: }
1.218     brouard  8599:  
1.126     brouard  8600: /************ Variance ******************/
1.235     brouard  8601:  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  8602:  {
1.361     brouard  8603:    /** Computes the matrix of variance covariance of health expectancies e.j= sum_i w_i e_ij where w_i depends of popbased,
                   8604:     * either cross-sectional or implied.
                   8605:     * return vareij[i][j][(int)age]=cov(e.i,e.j)=sum_h sum_k trgrad(h_p.i) V(theta) grad(k_p.k) Equation 20
1.279     brouard  8606:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   8607:     * double **newm;
                   8608:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   8609:     */
1.218     brouard  8610:   
                   8611:    /* int movingaverage(); */
                   8612:    double **dnewm,**doldm;
                   8613:    double **dnewmp,**doldmp;
                   8614:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  8615:    int first=0;
1.218     brouard  8616:    int k;
                   8617:    double *xp;
1.279     brouard  8618:    double **gp, **gm;  /**< for var eij */
                   8619:    double ***gradg, ***trgradg; /**< for var eij */
                   8620:    double **gradgp, **trgradgp; /**< for var p point j */
                   8621:    double *gpp, *gmp; /**< for var p point j */
1.362     brouard  8622:    double **varppt; /**< for var p.3 p.death nlstate+1 to nlstate+ndeath */
1.218     brouard  8623:    double ***p3mat;
                   8624:    double age,agelim, hf;
                   8625:    /* double ***mobaverage; */
                   8626:    int theta;
                   8627:    char digit[4];
                   8628:    char digitp[25];
                   8629: 
                   8630:    char fileresprobmorprev[FILENAMELENGTH];
                   8631: 
                   8632:    if(popbased==1){
                   8633:      if(mobilav!=0)
                   8634:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   8635:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   8636:    }
                   8637:    else 
                   8638:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  8639: 
1.218     brouard  8640:    /* if (mobilav!=0) { */
                   8641:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8642:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   8643:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   8644:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   8645:    /*   } */
                   8646:    /* } */
                   8647: 
                   8648:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   8649:    sprintf(digit,"%-d",ij);
                   8650:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   8651:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   8652:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   8653:    strcat(fileresprobmorprev,fileresu);
                   8654:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   8655:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   8656:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   8657:    }
                   8658:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8659:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8660:    pstamp(ficresprobmorprev);
                   8661:    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  8662:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  8663: 
                   8664:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   8665:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   8666:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   8667:    /* } */
                   8668:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  8669:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  8670:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  8671:    }
1.337     brouard  8672:    /* for(j=1;j<=cptcoveff;j++)  */
                   8673:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  8674:    fprintf(ficresprobmorprev,"\n");
                   8675: 
1.218     brouard  8676:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   8677:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   8678:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   8679:      for(i=1; i<=nlstate;i++)
                   8680:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   8681:    }  
                   8682:    fprintf(ficresprobmorprev,"\n");
                   8683:   
                   8684:    fprintf(ficgp,"\n# Routine varevsij");
                   8685:    fprintf(ficgp,"\nunset title \n");
                   8686:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   8687:    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");
                   8688:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  8689: 
1.361     brouard  8690:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); /* In fact, currently a double */
1.218     brouard  8691:    pstamp(ficresvij);
                   8692:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   8693:    if(popbased==1)
                   8694:      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);
                   8695:    else
                   8696:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   8697:    fprintf(ficresvij,"# Age");
                   8698:    for(i=1; i<=nlstate;i++)
                   8699:      for(j=1; j<=nlstate;j++)
                   8700:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   8701:    fprintf(ficresvij,"\n");
                   8702: 
                   8703:    xp=vector(1,npar);
                   8704:    dnewm=matrix(1,nlstate,1,npar);
                   8705:    doldm=matrix(1,nlstate,1,nlstate);
                   8706:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   8707:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8708: 
                   8709:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   8710:    gpp=vector(nlstate+1,nlstate+ndeath);
                   8711:    gmp=vector(nlstate+1,nlstate+ndeath);
                   8712:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  8713:   
1.218     brouard  8714:    if(estepm < stepm){
                   8715:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   8716:    }
                   8717:    else  hstepm=estepm;   
                   8718:    /* For example we decided to compute the life expectancy with the smallest unit */
                   8719:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8720:       nhstepm is the number of hstepm from age to agelim 
                   8721:       nstepm is the number of stepm from age to agelim. 
                   8722:       Look at function hpijx to understand why because of memory size limitations, 
                   8723:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   8724:       survival function given by stepm (the optimization length). Unfortunately it
                   8725:       means that if the survival funtion is printed every two years of age and if
                   8726:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8727:       results. So we changed our mind and took the option of the best precision.
                   8728:    */
                   8729:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8730:    agelim = AGESUP;
                   8731:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8732:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8733:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8734:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8735:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   8736:      gp=matrix(0,nhstepm,1,nlstate);
                   8737:      gm=matrix(0,nhstepm,1,nlstate);
                   8738:                
                   8739:                
                   8740:      for(theta=1; theta <=npar; theta++){
                   8741:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   8742:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8743:        }
1.279     brouard  8744:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   8745:        * returns into prlim .
1.288     brouard  8746:        */
1.242     brouard  8747:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  8748: 
                   8749:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  8750:        if (popbased==1) {
                   8751:         if(mobilav ==0){
                   8752:           for(i=1; i<=nlstate;i++)
                   8753:             prlim[i][i]=probs[(int)age][i][ij];
                   8754:         }else{ /* mobilav */ 
                   8755:           for(i=1; i<=nlstate;i++)
                   8756:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8757:         }
                   8758:        }
1.361     brouard  8759:        /**< Computes the shifted plus (gp) transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  8760:        */                      
                   8761:        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  8762:        /**< 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  8763:        * at horizon h in state j including mortality.
                   8764:        */
1.218     brouard  8765:        for(j=1; j<= nlstate; j++){
                   8766:         for(h=0; h<=nhstepm; h++){
                   8767:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
1.361     brouard  8768:             gp[h][j] += prlim[i][i]*p3mat[i][j][h]; /* gp[h][j]= w_i h_pij */
1.218     brouard  8769:         }
                   8770:        }
1.279     brouard  8771:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  8772:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  8773:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  8774:        */
1.361     brouard  8775:        for(j=nlstate+1;j<=nlstate+ndeath;j++){ /* Currently only once for theta plus  p.3(age) Sum_i wi pi3*/
1.218     brouard  8776:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   8777:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  8778:        }
                   8779:        
                   8780:        /* Again with minus shift */
1.218     brouard  8781:                        
                   8782:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   8783:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8784: 
1.242     brouard  8785:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  8786:                        
                   8787:        if (popbased==1) {
                   8788:         if(mobilav ==0){
                   8789:           for(i=1; i<=nlstate;i++)
                   8790:             prlim[i][i]=probs[(int)age][i][ij];
                   8791:         }else{ /* mobilav */ 
                   8792:           for(i=1; i<=nlstate;i++)
                   8793:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8794:         }
                   8795:        }
                   8796:                        
1.361     brouard  8797:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Still minus */
1.218     brouard  8798:                        
1.361     brouard  8799:        for(j=1; j<= nlstate; j++){  /* gm[h][j]= Sum_i of wi * pij =  h_p.j */
1.218     brouard  8800:         for(h=0; h<=nhstepm; h++){
                   8801:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   8802:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   8803:         }
                   8804:        }
                   8805:        /* This for computing probability of death (h=1 means
                   8806:          computed over hstepm matrices product = hstepm*stepm months) 
1.361     brouard  8807:          as a weighted average of prlim. j is death. gmp[3]=sum_i w_i*p_i3=p.3 minus theta
1.218     brouard  8808:        */
1.361     brouard  8809:        for(j=nlstate+1;j<=nlstate+ndeath;j++){  /* Currently only once theta_minus  p.3=Sum_i wi pi3*/
1.218     brouard  8810:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   8811:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   8812:        }    
1.279     brouard  8813:        /* end shifting computations */
                   8814: 
1.361     brouard  8815:        /**< Computing gradient of p.j matrix at horizon h and still for one parameter of vector theta
                   8816:        * equation 31 and 32
1.279     brouard  8817:        */
1.361     brouard  8818:        for(j=1; j<= nlstate; j++) /* computes grad p.j(x, over each  h) where p.j is Sum_i w_i*pij(x over h)
                   8819:                                  * equation 24 */
1.218     brouard  8820:         for(h=0; h<=nhstepm; h++){
                   8821:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   8822:         }
1.361     brouard  8823:        /**< Gradient of overall mortality p.3 (or p.death) 
1.279     brouard  8824:        */
1.361     brouard  8825:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* computes grad of p.3 from wi+pi3 grad p.3 (theta) */
1.218     brouard  8826:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   8827:        }
                   8828:                        
                   8829:      } /* End theta */
1.279     brouard  8830:      
1.361     brouard  8831:      /* We got the gradient matrix for each theta and each state j of gradg(h]theta][j)=grad(_hp.j(theta) */           
                   8832:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
1.218     brouard  8833:                
1.361     brouard  8834:      for(h=0; h<=nhstepm; h++) /* veij */ /* computes the transposed of grad  (_hp.j(theta)*/
1.218     brouard  8835:        for(j=1; j<=nlstate;j++)
                   8836:         for(theta=1; theta <=npar; theta++)
                   8837:           trgradg[h][j][theta]=gradg[h][theta][j];
                   8838:                
1.361     brouard  8839:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* computes transposed of grad p.3 (theta)*/
1.218     brouard  8840:        for(theta=1; theta <=npar; theta++)
                   8841:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  8842:      /**< as well as its transposed matrix 
                   8843:       */               
1.218     brouard  8844:                
                   8845:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8846:      for(i=1;i<=nlstate;i++)
                   8847:        for(j=1;j<=nlstate;j++)
                   8848:         vareij[i][j][(int)age] =0.;
1.279     brouard  8849: 
                   8850:      /* Computing trgradg by matcov by gradg at age and summing over h
1.361     brouard  8851:       * and k (nhstepm) formula 32 of article
                   8852:       * Lievre-Brouard-Heathcote so that for each j, computes the cov(e.j,e.k) (formula 31).
                   8853:       * for given h and k computes trgradg[h](i,j) matcov (theta) gradg(k)(i,j) into vareij[i][j] which is
                   8854:       cov(e.i,e.j) and sums on h and k
                   8855:       * including the covariances.
1.279     brouard  8856:       */
                   8857:      
1.218     brouard  8858:      for(h=0;h<=nhstepm;h++){
                   8859:        for(k=0;k<=nhstepm;k++){
                   8860:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   8861:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   8862:         for(i=1;i<=nlstate;i++)
                   8863:           for(j=1;j<=nlstate;j++)
1.361     brouard  8864:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf; /* This is vareij=sum_h sum_k trgrad(h_pij) V(theta) grad(k_pij)
                   8865:                                                             including the covariances of e.j */
1.218     brouard  8866:        }
                   8867:      }
                   8868:                
1.361     brouard  8869:      /* Mortality: pptj is p.3 or p.death = trgradgp by cov by gradgp, variance of
                   8870:       * p.3=1-p..=1-sum i p.i  overall mortality computed directly because
1.279     brouard  8871:       * we compute the grad (wix pijx) instead of grad (pijx),even if
1.361     brouard  8872:       * wix is independent of theta. 
1.279     brouard  8873:       */
1.218     brouard  8874:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   8875:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   8876:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   8877:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
1.361     brouard  8878:         varppt[j][i]=doldmp[j][i];  /* This is the variance of p.3 */
1.218     brouard  8879:      /* end ppptj */
                   8880:      /*  x centered again */
                   8881:                
1.242     brouard  8882:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  8883:                
                   8884:      if (popbased==1) {
                   8885:        if(mobilav ==0){
                   8886:         for(i=1; i<=nlstate;i++)
                   8887:           prlim[i][i]=probs[(int)age][i][ij];
                   8888:        }else{ /* mobilav */ 
                   8889:         for(i=1; i<=nlstate;i++)
                   8890:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   8891:        }
                   8892:      }
                   8893:                
                   8894:      /* This for computing probability of death (h=1 means
                   8895:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   8896:        as a weighted average of prlim.
                   8897:      */
1.235     brouard  8898:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  8899:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8900:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
1.361     brouard  8901:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; /* gmp[j] is p.3 */
1.218     brouard  8902:      }    
                   8903:      /* end probability of death */
                   8904:                
                   8905:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   8906:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
1.361     brouard  8907:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));/* p.3 (STD p.3) */
1.218     brouard  8908:        for(i=1; i<=nlstate;i++){
1.361     brouard  8909:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]); /* wi, pi3 */
1.218     brouard  8910:        }
                   8911:      } 
                   8912:      fprintf(ficresprobmorprev,"\n");
                   8913:                
                   8914:      fprintf(ficresvij,"%.0f ",age );
                   8915:      for(i=1; i<=nlstate;i++)
                   8916:        for(j=1; j<=nlstate;j++){
                   8917:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   8918:        }
                   8919:      fprintf(ficresvij,"\n");
                   8920:      free_matrix(gp,0,nhstepm,1,nlstate);
                   8921:      free_matrix(gm,0,nhstepm,1,nlstate);
                   8922:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   8923:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   8924:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8925:    } /* End age */
                   8926:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   8927:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   8928:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   8929:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   8930:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   8931:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   8932:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   8933:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   8934:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   8935:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   8936:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8937:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8938:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   8939:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   8940:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   8941:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   8942:    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);
                   8943:    /*  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  8944:     */
1.218     brouard  8945:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   8946:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  8947: 
1.218     brouard  8948:    free_vector(xp,1,npar);
                   8949:    free_matrix(doldm,1,nlstate,1,nlstate);
                   8950:    free_matrix(dnewm,1,nlstate,1,npar);
                   8951:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8952:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   8953:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8954:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8955:    fclose(ficresprobmorprev);
                   8956:    fflush(ficgp);
                   8957:    fflush(fichtm); 
                   8958:  }  /* end varevsij */
1.126     brouard  8959: 
                   8960: /************ Variance of prevlim ******************/
1.269     brouard  8961:  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  8962: {
1.205     brouard  8963:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  8964:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  8965: 
1.268     brouard  8966:   double **dnewmpar,**doldm;
1.126     brouard  8967:   int i, j, nhstepm, hstepm;
                   8968:   double *xp;
                   8969:   double *gp, *gm;
                   8970:   double **gradg, **trgradg;
1.208     brouard  8971:   double **mgm, **mgp;
1.126     brouard  8972:   double age,agelim;
                   8973:   int theta;
                   8974:   
                   8975:   pstamp(ficresvpl);
1.288     brouard  8976:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  8977:   fprintf(ficresvpl,"# Age ");
                   8978:   if(nresult >=1)
                   8979:     fprintf(ficresvpl," Result# ");
1.126     brouard  8980:   for(i=1; i<=nlstate;i++)
                   8981:       fprintf(ficresvpl," %1d-%1d",i,i);
                   8982:   fprintf(ficresvpl,"\n");
                   8983: 
                   8984:   xp=vector(1,npar);
1.268     brouard  8985:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  8986:   doldm=matrix(1,nlstate,1,nlstate);
                   8987:   
                   8988:   hstepm=1*YEARM; /* Every year of age */
                   8989:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   8990:   agelim = AGESUP;
                   8991:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8992:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8993:     if (stepm >= YEARM) hstepm=1;
                   8994:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8995:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  8996:     mgp=matrix(1,npar,1,nlstate);
                   8997:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  8998:     gp=vector(1,nlstate);
                   8999:     gm=vector(1,nlstate);
                   9000: 
                   9001:     for(theta=1; theta <=npar; theta++){
                   9002:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9003:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9004:       }
1.288     brouard  9005:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   9006:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   9007:       /* else */
                   9008:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  9009:       for(i=1;i<=nlstate;i++){
1.126     brouard  9010:        gp[i] = prlim[i][i];
1.208     brouard  9011:        mgp[theta][i] = prlim[i][i];
                   9012:       }
1.126     brouard  9013:       for(i=1; i<=npar; i++) /* Computes gradient */
                   9014:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  9015:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   9016:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   9017:       /* else */
                   9018:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  9019:       for(i=1;i<=nlstate;i++){
1.126     brouard  9020:        gm[i] = prlim[i][i];
1.208     brouard  9021:        mgm[theta][i] = prlim[i][i];
                   9022:       }
1.126     brouard  9023:       for(i=1;i<=nlstate;i++)
                   9024:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  9025:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  9026:     } /* End theta */
                   9027: 
                   9028:     trgradg =matrix(1,nlstate,1,npar);
                   9029: 
                   9030:     for(j=1; j<=nlstate;j++)
                   9031:       for(theta=1; theta <=npar; theta++)
                   9032:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  9033:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9034:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9035:     /*   for(j=1; j<=nlstate;j++){ */
                   9036:     /*         printf(" %d ",j); */
                   9037:     /*         for(theta=1; theta <=npar; theta++) */
                   9038:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9039:     /*         printf("\n "); */
                   9040:     /*   } */
                   9041:     /* } */
                   9042:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9043:     /*   printf("\n gradg %d ",(int)age); */
                   9044:     /*   for(j=1; j<=nlstate;j++){ */
                   9045:     /*         printf("%d ",j); */
                   9046:     /*         for(theta=1; theta <=npar; theta++) */
                   9047:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9048:     /*         printf("\n "); */
                   9049:     /*   } */
                   9050:     /* } */
1.126     brouard  9051: 
                   9052:     for(i=1;i<=nlstate;i++)
                   9053:       varpl[i][(int)age] =0.;
1.209     brouard  9054:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  9055:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9056:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9057:     }else{
1.268     brouard  9058:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9059:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9060:     }
1.126     brouard  9061:     for(i=1;i<=nlstate;i++)
                   9062:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9063: 
                   9064:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  9065:     if(nresult >=1)
                   9066:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  9067:     for(i=1; i<=nlstate;i++){
1.126     brouard  9068:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  9069:       /* for(j=1;j<=nlstate;j++) */
                   9070:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   9071:     }
1.126     brouard  9072:     fprintf(ficresvpl,"\n");
                   9073:     free_vector(gp,1,nlstate);
                   9074:     free_vector(gm,1,nlstate);
1.208     brouard  9075:     free_matrix(mgm,1,npar,1,nlstate);
                   9076:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  9077:     free_matrix(gradg,1,npar,1,nlstate);
                   9078:     free_matrix(trgradg,1,nlstate,1,npar);
                   9079:   } /* End age */
                   9080: 
                   9081:   free_vector(xp,1,npar);
                   9082:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  9083:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   9084: 
                   9085: }
                   9086: 
                   9087: 
                   9088: /************ Variance of backprevalence limit ******************/
1.269     brouard  9089:  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  9090: {
                   9091:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   9092:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   9093: 
                   9094:   double **dnewmpar,**doldm;
                   9095:   int i, j, nhstepm, hstepm;
                   9096:   double *xp;
                   9097:   double *gp, *gm;
                   9098:   double **gradg, **trgradg;
                   9099:   double **mgm, **mgp;
                   9100:   double age,agelim;
                   9101:   int theta;
                   9102:   
                   9103:   pstamp(ficresvbl);
                   9104:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   9105:   fprintf(ficresvbl,"# Age ");
                   9106:   if(nresult >=1)
                   9107:     fprintf(ficresvbl," Result# ");
                   9108:   for(i=1; i<=nlstate;i++)
                   9109:       fprintf(ficresvbl," %1d-%1d",i,i);
                   9110:   fprintf(ficresvbl,"\n");
                   9111: 
                   9112:   xp=vector(1,npar);
                   9113:   dnewmpar=matrix(1,nlstate,1,npar);
                   9114:   doldm=matrix(1,nlstate,1,nlstate);
                   9115:   
                   9116:   hstepm=1*YEARM; /* Every year of age */
                   9117:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   9118:   agelim = AGEINF;
                   9119:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   9120:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9121:     if (stepm >= YEARM) hstepm=1;
                   9122:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9123:     gradg=matrix(1,npar,1,nlstate);
                   9124:     mgp=matrix(1,npar,1,nlstate);
                   9125:     mgm=matrix(1,npar,1,nlstate);
                   9126:     gp=vector(1,nlstate);
                   9127:     gm=vector(1,nlstate);
                   9128: 
                   9129:     for(theta=1; theta <=npar; theta++){
                   9130:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9131:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9132:       }
                   9133:       if(mobilavproj > 0 )
                   9134:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9135:       else
                   9136:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9137:       for(i=1;i<=nlstate;i++){
                   9138:        gp[i] = bprlim[i][i];
                   9139:        mgp[theta][i] = bprlim[i][i];
                   9140:       }
                   9141:      for(i=1; i<=npar; i++) /* Computes gradient */
                   9142:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   9143:        if(mobilavproj > 0 )
                   9144:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9145:        else
                   9146:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9147:       for(i=1;i<=nlstate;i++){
                   9148:        gm[i] = bprlim[i][i];
                   9149:        mgm[theta][i] = bprlim[i][i];
                   9150:       }
                   9151:       for(i=1;i<=nlstate;i++)
                   9152:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   9153:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   9154:     } /* End theta */
                   9155: 
                   9156:     trgradg =matrix(1,nlstate,1,npar);
                   9157: 
                   9158:     for(j=1; j<=nlstate;j++)
                   9159:       for(theta=1; theta <=npar; theta++)
                   9160:        trgradg[j][theta]=gradg[theta][j];
                   9161:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9162:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9163:     /*   for(j=1; j<=nlstate;j++){ */
                   9164:     /*         printf(" %d ",j); */
                   9165:     /*         for(theta=1; theta <=npar; theta++) */
                   9166:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9167:     /*         printf("\n "); */
                   9168:     /*   } */
                   9169:     /* } */
                   9170:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9171:     /*   printf("\n gradg %d ",(int)age); */
                   9172:     /*   for(j=1; j<=nlstate;j++){ */
                   9173:     /*         printf("%d ",j); */
                   9174:     /*         for(theta=1; theta <=npar; theta++) */
                   9175:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9176:     /*         printf("\n "); */
                   9177:     /*   } */
                   9178:     /* } */
                   9179: 
                   9180:     for(i=1;i<=nlstate;i++)
                   9181:       varbpl[i][(int)age] =0.;
                   9182:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   9183:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9184:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9185:     }else{
                   9186:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9187:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9188:     }
                   9189:     for(i=1;i<=nlstate;i++)
                   9190:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9191: 
                   9192:     fprintf(ficresvbl,"%.0f ",age );
                   9193:     if(nresult >=1)
                   9194:       fprintf(ficresvbl,"%d ",nres );
                   9195:     for(i=1; i<=nlstate;i++)
                   9196:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   9197:     fprintf(ficresvbl,"\n");
                   9198:     free_vector(gp,1,nlstate);
                   9199:     free_vector(gm,1,nlstate);
                   9200:     free_matrix(mgm,1,npar,1,nlstate);
                   9201:     free_matrix(mgp,1,npar,1,nlstate);
                   9202:     free_matrix(gradg,1,npar,1,nlstate);
                   9203:     free_matrix(trgradg,1,nlstate,1,npar);
                   9204:   } /* End age */
                   9205: 
                   9206:   free_vector(xp,1,npar);
                   9207:   free_matrix(doldm,1,nlstate,1,npar);
                   9208:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  9209: 
                   9210: }
                   9211: 
                   9212: /************ Variance of one-step probabilities  ******************/
                   9213: 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  9214:  {
                   9215:    int i, j=0,  k1, l1, tj;
                   9216:    int k2, l2, j1,  z1;
                   9217:    int k=0, l;
                   9218:    int first=1, first1, first2;
1.326     brouard  9219:    int nres=0; /* New */
1.222     brouard  9220:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   9221:    double **dnewm,**doldm;
                   9222:    double *xp;
                   9223:    double *gp, *gm;
                   9224:    double **gradg, **trgradg;
                   9225:    double **mu;
                   9226:    double age, cov[NCOVMAX+1];
                   9227:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   9228:    int theta;
                   9229:    char fileresprob[FILENAMELENGTH];
                   9230:    char fileresprobcov[FILENAMELENGTH];
                   9231:    char fileresprobcor[FILENAMELENGTH];
                   9232:    double ***varpij;
                   9233: 
                   9234:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  9235:    strcat(fileresprob,fileresu);
1.222     brouard  9236:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   9237:      printf("Problem with resultfile: %s\n", fileresprob);
                   9238:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   9239:    }
                   9240:    strcpy(fileresprobcov,"PROBCOV_"); 
                   9241:    strcat(fileresprobcov,fileresu);
                   9242:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   9243:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   9244:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   9245:    }
                   9246:    strcpy(fileresprobcor,"PROBCOR_"); 
                   9247:    strcat(fileresprobcor,fileresu);
                   9248:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   9249:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   9250:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   9251:    }
                   9252:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9253:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9254:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9255:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9256:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9257:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9258:    pstamp(ficresprob);
                   9259:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   9260:    fprintf(ficresprob,"# Age");
                   9261:    pstamp(ficresprobcov);
                   9262:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   9263:    fprintf(ficresprobcov,"# Age");
                   9264:    pstamp(ficresprobcor);
                   9265:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   9266:    fprintf(ficresprobcor,"# Age");
1.126     brouard  9267: 
                   9268: 
1.222     brouard  9269:    for(i=1; i<=nlstate;i++)
                   9270:      for(j=1; j<=(nlstate+ndeath);j++){
                   9271:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   9272:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   9273:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   9274:      }  
                   9275:    /* fprintf(ficresprob,"\n");
                   9276:       fprintf(ficresprobcov,"\n");
                   9277:       fprintf(ficresprobcor,"\n");
                   9278:    */
                   9279:    xp=vector(1,npar);
                   9280:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9281:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9282:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   9283:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   9284:    first=1;
                   9285:    fprintf(ficgp,"\n# Routine varprob");
                   9286:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   9287:    fprintf(fichtm,"\n");
                   9288: 
1.288     brouard  9289:    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  9290:    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);
                   9291:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  9292: and drawn. It helps understanding how is the covariance between two incidences.\
                   9293:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  9294:    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  9295: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   9296: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   9297: standard deviations wide on each axis. <br>\
                   9298:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   9299:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   9300: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   9301: 
1.222     brouard  9302:    cov[1]=1;
                   9303:    /* tj=cptcoveff; */
1.225     brouard  9304:    tj = (int) pow(2,cptcoveff);
1.222     brouard  9305:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   9306:    j1=0;
1.332     brouard  9307: 
                   9308:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   9309:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  9310:      /* 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  9311:      if(tj != 1 && TKresult[nres]!= j1)
                   9312:        continue;
                   9313: 
                   9314:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   9315:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   9316:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  9317:      if  (cptcovn>0) {
1.334     brouard  9318:        fprintf(ficresprob, "\n#********** Variable ");
                   9319:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   9320:        fprintf(ficgp, "\n#********** Variable ");
                   9321:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   9322:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   9323: 
                   9324:        /* Including quantitative variables of the resultline to be done */
                   9325:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  9326:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  9327:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   9328:         /* 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  9329:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   9330:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   9331:             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  */
                   9332:             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  */
                   9333:             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  */
                   9334:             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  */
                   9335:             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  */
                   9336:             fprintf(ficresprob,"fixed ");
                   9337:             fprintf(ficresprobcov,"fixed ");
                   9338:             fprintf(ficgp,"fixed ");
                   9339:             fprintf(fichtmcov,"fixed ");
                   9340:             fprintf(ficresprobcor,"fixed ");
                   9341:           }else{
                   9342:             fprintf(ficresprob,"varyi ");
                   9343:             fprintf(ficresprobcov,"varyi ");
                   9344:             fprintf(ficgp,"varyi ");
                   9345:             fprintf(fichtmcov,"varyi ");
                   9346:             fprintf(ficresprobcor,"varyi ");
                   9347:           }
                   9348:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   9349:           /* For each selected (single) quantitative value */
1.337     brouard  9350:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  9351:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   9352:             fprintf(ficresprob,"fixed ");
                   9353:             fprintf(ficresprobcov,"fixed ");
                   9354:             fprintf(ficgp,"fixed ");
                   9355:             fprintf(fichtmcov,"fixed ");
                   9356:             fprintf(ficresprobcor,"fixed ");
                   9357:           }else{
                   9358:             fprintf(ficresprob,"varyi ");
                   9359:             fprintf(ficresprobcov,"varyi ");
                   9360:             fprintf(ficgp,"varyi ");
                   9361:             fprintf(fichtmcov,"varyi ");
                   9362:             fprintf(ficresprobcor,"varyi ");
                   9363:           }
                   9364:         }else{
                   9365:           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 */
                   9366:           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 */
                   9367:           exit(1);
                   9368:         }
                   9369:        } /* End loop on variable of this resultline */
                   9370:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  9371:        fprintf(ficresprob, "**********\n#\n");
                   9372:        fprintf(ficresprobcov, "**********\n#\n");
                   9373:        fprintf(ficgp, "**********\n#\n");
                   9374:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   9375:        fprintf(ficresprobcor, "**********\n#");    
                   9376:        if(invalidvarcomb[j1]){
                   9377:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   9378:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   9379:         continue;
                   9380:        }
                   9381:      }
                   9382:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   9383:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9384:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   9385:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  9386:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  9387:        cov[2]=age;
                   9388:        if(nagesqr==1)
                   9389:         cov[3]= age*age;
1.334     brouard  9390:        /* New code end of combination but for each resultline */
                   9391:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  9392:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  9393:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  9394:         }else{
1.334     brouard  9395:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  9396:         }
1.334     brouard  9397:        }/* End of loop on model equation */
                   9398: /* Old code */
                   9399:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   9400:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   9401:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   9402:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   9403:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   9404:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   9405:        /*                                                                  * 1  1 1 1 1 */
                   9406:        /*                                                                  * 2  2 1 1 1 */
                   9407:        /*                                                                  * 3  1 2 1 1 */
                   9408:        /*                                                                  *\/ */
                   9409:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   9410:        /* } */
                   9411:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   9412:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   9413:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   9414:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   9415:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   9416:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   9417:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9418:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   9419:        /*         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]); */
                   9420:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   9421:        /*         /\* exit(1); *\/ */
                   9422:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   9423:        /*       } */
                   9424:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9425:        /* } */
                   9426:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   9427:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   9428:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9429:        /*           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]])]; */
                   9430:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9431:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   9432:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   9433:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   9434:        /*         } */
                   9435:        /*       }else{ */
                   9436:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9437:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   9438:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   9439:        /*         }else{ */
                   9440:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   9441:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   9442:        /*         } */
                   9443:        /*       } */
                   9444:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9445:        /* } */                 
1.326     brouard  9446: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  9447:        for(theta=1; theta <=npar; theta++){
                   9448:         for(i=1; i<=npar; i++)
                   9449:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  9450:                                
1.222     brouard  9451:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  9452:                                
1.222     brouard  9453:         k=0;
                   9454:         for(i=1; i<= (nlstate); i++){
                   9455:           for(j=1; j<=(nlstate+ndeath);j++){
                   9456:             k=k+1;
                   9457:             gp[k]=pmmij[i][j];
                   9458:           }
                   9459:         }
1.220     brouard  9460:                                
1.222     brouard  9461:         for(i=1; i<=npar; i++)
                   9462:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  9463:                                
1.222     brouard  9464:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   9465:         k=0;
                   9466:         for(i=1; i<=(nlstate); i++){
                   9467:           for(j=1; j<=(nlstate+ndeath);j++){
                   9468:             k=k+1;
                   9469:             gm[k]=pmmij[i][j];
                   9470:           }
                   9471:         }
1.220     brouard  9472:                                
1.222     brouard  9473:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   9474:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   9475:        }
1.126     brouard  9476: 
1.222     brouard  9477:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   9478:         for(theta=1; theta <=npar; theta++)
                   9479:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  9480:                        
1.222     brouard  9481:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   9482:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  9483:                        
1.222     brouard  9484:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  9485:                        
1.222     brouard  9486:        k=0;
                   9487:        for(i=1; i<=(nlstate); i++){
                   9488:         for(j=1; j<=(nlstate+ndeath);j++){
                   9489:           k=k+1;
                   9490:           mu[k][(int) age]=pmmij[i][j];
                   9491:         }
                   9492:        }
                   9493:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   9494:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   9495:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  9496:                        
1.222     brouard  9497:        /*printf("\n%d ",(int)age);
                   9498:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9499:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9500:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9501:         }*/
1.220     brouard  9502:                        
1.222     brouard  9503:        fprintf(ficresprob,"\n%d ",(int)age);
                   9504:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   9505:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  9506:                        
1.222     brouard  9507:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   9508:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   9509:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9510:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   9511:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   9512:        }
                   9513:        i=0;
                   9514:        for (k=1; k<=(nlstate);k++){
                   9515:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   9516:           i++;
                   9517:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   9518:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   9519:           for (j=1; j<=i;j++){
                   9520:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   9521:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   9522:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   9523:           }
                   9524:         }
                   9525:        }/* end of loop for state */
                   9526:      } /* end of loop for age */
                   9527:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9528:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9529:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9530:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9531:     
                   9532:      /* Confidence intervalle of pij  */
                   9533:      /*
                   9534:        fprintf(ficgp,"\nunset parametric;unset label");
                   9535:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   9536:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   9537:        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);
                   9538:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   9539:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   9540:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   9541:      */
                   9542:                
                   9543:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   9544:      first1=1;first2=2;
                   9545:      for (k2=1; k2<=(nlstate);k2++){
                   9546:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   9547:         if(l2==k2) continue;
                   9548:         j=(k2-1)*(nlstate+ndeath)+l2;
                   9549:         for (k1=1; k1<=(nlstate);k1++){
                   9550:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   9551:             if(l1==k1) continue;
                   9552:             i=(k1-1)*(nlstate+ndeath)+l1;
                   9553:             if(i<=j) continue;
                   9554:             for (age=bage; age<=fage; age ++){ 
                   9555:               if ((int)age %5==0){
                   9556:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   9557:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9558:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9559:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   9560:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   9561:                 c12=cv12/sqrt(v1*v2);
                   9562:                 /* Computing eigen value of matrix of covariance */
                   9563:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9564:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9565:                 if ((lc2 <0) || (lc1 <0) ){
                   9566:                   if(first2==1){
                   9567:                     first1=0;
                   9568:                     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);
                   9569:                   }
                   9570:                   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);
                   9571:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   9572:                   /* lc2=fabs(lc2); */
                   9573:                 }
1.220     brouard  9574:                                                                
1.222     brouard  9575:                 /* Eigen vectors */
1.280     brouard  9576:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   9577:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9578:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9579:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   9580:                 }else
                   9581:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  9582:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   9583:                 v21=(lc1-v1)/cv12*v11;
                   9584:                 v12=-v21;
                   9585:                 v22=v11;
                   9586:                 tnalp=v21/v11;
                   9587:                 if(first1==1){
                   9588:                   first1=0;
                   9589:                   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);
                   9590:                 }
                   9591:                 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);
                   9592:                 /*printf(fignu*/
                   9593:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   9594:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   9595:                 if(first==1){
                   9596:                   first=0;
                   9597:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   9598:                   fprintf(ficgp,"\nset parametric;unset label");
                   9599:                   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);
                   9600:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  9601:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  9602:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  9603: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  9604:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   9605:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9606:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9607:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   9608:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9609:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9610:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9611:                   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  9612:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   9613:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  9614:                 }else{
                   9615:                   first=0;
                   9616:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   9617:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9618:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9619:                   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  9620:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   9621:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  9622:                 }/* if first */
                   9623:               } /* age mod 5 */
                   9624:             } /* end loop age */
                   9625:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9626:             first=1;
                   9627:           } /*l12 */
                   9628:         } /* k12 */
                   9629:        } /*l1 */
                   9630:      }/* k1 */
1.332     brouard  9631:    }  /* loop on combination of covariates j1 */
1.326     brouard  9632:    } /* loop on nres */
1.222     brouard  9633:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   9634:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   9635:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9636:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   9637:    free_vector(xp,1,npar);
                   9638:    fclose(ficresprob);
                   9639:    fclose(ficresprobcov);
                   9640:    fclose(ficresprobcor);
                   9641:    fflush(ficgp);
                   9642:    fflush(fichtmcov);
                   9643:  }
1.126     brouard  9644: 
                   9645: 
                   9646: /******************* Printing html file ***********/
1.201     brouard  9647: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9648:                  int lastpass, int stepm, int weightopt, char model[],\
                   9649:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  9650:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   9651:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   9652:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.359     brouard  9653:   int jj1, k1, cpt, nres;
1.319     brouard  9654:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  9655:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   9656:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   9657: </ul>");
1.319     brouard  9658: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   9659: /* </ul>", model); */
1.214     brouard  9660:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   9661:    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",
                   9662:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  9663:    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  9664:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   9665:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  9666:    fprintf(fichtm,"\
                   9667:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  9668:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  9669:    fprintf(fichtm,"\
1.217     brouard  9670:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   9671:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   9672:    fprintf(fichtm,"\
1.288     brouard  9673:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9674:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  9675:    fprintf(fichtm,"\
1.288     brouard  9676:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  9677:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   9678:    fprintf(fichtm,"\
1.211     brouard  9679:  - (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  9680:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9681:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  9682:    if(prevfcast==1){
                   9683:      fprintf(fichtm,"\
                   9684:  - Prevalence projections by age and states:                           \
1.201     brouard  9685:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  9686:    }
1.126     brouard  9687: 
                   9688: 
1.225     brouard  9689:    m=pow(2,cptcoveff);
1.222     brouard  9690:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9691: 
1.317     brouard  9692:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  9693: 
                   9694:    jj1=0;
                   9695: 
                   9696:    fprintf(fichtm," \n<ul>");
1.337     brouard  9697:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9698:      /* k1=nres; */
1.338     brouard  9699:      k1=TKresult[nres];
                   9700:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  9701:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9702:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9703:    /*     continue; */
1.264     brouard  9704:      jj1++;
                   9705:      if (cptcovn > 0) {
                   9706:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  9707:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9708:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9709:        }
1.337     brouard  9710:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9711:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9712:        /* } */
                   9713:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9714:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9715:        /* } */
1.264     brouard  9716:        fprintf(fichtm,"\">");
                   9717:        
                   9718:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9719:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9720:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9721:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9722:        }
1.337     brouard  9723:        /* fprintf(fichtm,"************ Results for covariates"); */
                   9724:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9725:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9726:        /* } */
                   9727:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9728:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9729:        /* } */
1.264     brouard  9730:        if(invalidvarcomb[k1]){
                   9731:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9732:         continue;
                   9733:        }
                   9734:        fprintf(fichtm,"</a></li>");
                   9735:      } /* cptcovn >0 */
                   9736:    }
1.317     brouard  9737:    fprintf(fichtm," \n</ul>");
1.264     brouard  9738: 
1.222     brouard  9739:    jj1=0;
1.237     brouard  9740: 
1.337     brouard  9741:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9742:      /* k1=nres; */
1.338     brouard  9743:      k1=TKresult[nres];
                   9744:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9745:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9746:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9747:    /*     continue; */
1.220     brouard  9748: 
1.222     brouard  9749:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9750:      jj1++;
                   9751:      if (cptcovn > 0) {
1.264     brouard  9752:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  9753:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9754:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9755:        }
1.337     brouard  9756:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9757:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9758:        /* } */
1.264     brouard  9759:        fprintf(fichtm,"\"</a>");
                   9760:  
1.222     brouard  9761:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9762:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9763:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9764:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9765:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   9766:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  9767:        }
1.230     brouard  9768:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  9769:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  9770:        if(invalidvarcomb[k1]){
                   9771:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   9772:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   9773:         continue;
                   9774:        }
                   9775:      }
                   9776:      /* aij, bij */
1.259     brouard  9777:      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  9778: <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  9779:      /* Pij */
1.241     brouard  9780:      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> \
                   9781: <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  9782:      /* Quasi-incidences */
                   9783:      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  9784:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  9785:  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  9786: 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> \
                   9787: <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  9788:      /* Survival functions (period) in state j */
                   9789:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9790:        fprintf(fichtm,"<br>\n- Survival functions in state %d. And probability to be observed in state %d being in state (1 to %d) at different ages. Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.329     brouard  9791:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9792:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  9793:      }
                   9794:      /* State specific survival functions (period) */
                   9795:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  9796:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
1.359     brouard  9797:  And probability to be observed in various states (up to %d) being in state %d at different ages.  Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. \
1.329     brouard  9798:  <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);
                   9799:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9800:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  9801:      }
1.288     brouard  9802:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  9803:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9804:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability for a person being in state (1 to %d) at different ages, to be alive in state %d some years after. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.338     brouard  9805:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  9806:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  9807:      }
1.296     brouard  9808:      if(prevbcast==1){
1.288     brouard  9809:        /* Backward prevalence in each health state */
1.222     brouard  9810:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  9811:         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);
                   9812:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   9813:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  9814:        }
1.217     brouard  9815:      }
1.222     brouard  9816:      if(prevfcast==1){
1.288     brouard  9817:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  9818:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  9819:         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);
                   9820:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   9821:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   9822:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  9823:        }
                   9824:      }
1.296     brouard  9825:      if(prevbcast==1){
1.268     brouard  9826:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   9827:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  9828:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
1.359     brouard  9829:  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 \
                   9830:  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  9831: 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);
                   9832:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   9833:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  9834:        }
                   9835:      }
1.220     brouard  9836:         
1.222     brouard  9837:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  9838:        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);
                   9839:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   9840:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  9841:      }
                   9842:      /* } /\* end i1 *\/ */
1.337     brouard  9843:    }/* End k1=nres */
1.222     brouard  9844:    fprintf(fichtm,"</ul>");
1.126     brouard  9845: 
1.222     brouard  9846:    fprintf(fichtm,"\
1.126     brouard  9847: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  9848:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  9849:  - 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  9850: But because parameters are usually highly correlated (a higher incidence of disability \
                   9851: and a higher incidence of recovery can give very close observed transition) it might \
                   9852: be very useful to look not only at linear confidence intervals estimated from the \
                   9853: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   9854: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   9855: covariance matrix of the one-step probabilities. \
                   9856: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  9857: 
1.222     brouard  9858:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   9859:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   9860:    fprintf(fichtm,"\
1.126     brouard  9861:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9862:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  9863: 
1.222     brouard  9864:    fprintf(fichtm,"\
1.126     brouard  9865:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9866:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   9867:    fprintf(fichtm,"\
1.126     brouard  9868:  - 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): \
                   9869:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9870:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  9871:    fprintf(fichtm,"\
1.126     brouard  9872:  - (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): \
                   9873:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9874:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  9875:    fprintf(fichtm,"\
1.288     brouard  9876:  - 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  9877:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   9878:    fprintf(fichtm,"\
1.128     brouard  9879:  - 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  9880:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   9881:    fprintf(fichtm,"\
1.288     brouard  9882:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  9883:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  9884: 
                   9885: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   9886: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   9887: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   9888: /*     <br>",fileres,fileres,fileres,fileres); */
                   9889: /*  else  */
1.338     brouard  9890: /*    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  9891:    fflush(fichtm);
1.126     brouard  9892: 
1.225     brouard  9893:    m=pow(2,cptcoveff);
1.222     brouard  9894:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9895: 
1.317     brouard  9896:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   9897: 
                   9898:   jj1=0;
                   9899: 
                   9900:    fprintf(fichtm," \n<ul>");
1.337     brouard  9901:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9902:      /* k1=nres; */
1.338     brouard  9903:      k1=TKresult[nres];
1.337     brouard  9904:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9905:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9906:      /*   continue; */
1.317     brouard  9907:      jj1++;
                   9908:      if (cptcovn > 0) {
                   9909:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  9910:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9911:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9912:        }
                   9913:        fprintf(fichtm,"\">");
                   9914:        
                   9915:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9916:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9917:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9918:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9919:        }
                   9920:        if(invalidvarcomb[k1]){
                   9921:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9922:         continue;
                   9923:        }
                   9924:        fprintf(fichtm,"</a></li>");
                   9925:      } /* cptcovn >0 */
1.337     brouard  9926:    } /* End nres */
1.317     brouard  9927:    fprintf(fichtm," \n</ul>");
                   9928: 
1.222     brouard  9929:    jj1=0;
1.237     brouard  9930: 
1.241     brouard  9931:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9932:      /* k1=nres; */
1.338     brouard  9933:      k1=TKresult[nres];
                   9934:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9935:      /* for(k1=1; k1<=m;k1++){ */
                   9936:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9937:      /*   continue; */
1.222     brouard  9938:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9939:      jj1++;
1.126     brouard  9940:      if (cptcovn > 0) {
1.317     brouard  9941:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  9942:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9943:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9944:        }
                   9945:        fprintf(fichtm,"\"</a>");
                   9946:        
1.126     brouard  9947:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9948:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   9949:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9950:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9951:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  9952:        }
1.237     brouard  9953: 
1.338     brouard  9954:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  9955: 
1.222     brouard  9956:        if(invalidvarcomb[k1]){
                   9957:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   9958:         continue;
                   9959:        }
1.337     brouard  9960:      } /* If cptcovn >0 */
1.126     brouard  9961:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  9962:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  9963: 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);
                   9964:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   9965:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  9966:      }
                   9967:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.360     brouard  9968: health expectancies in each live state (1 to %d) with confidence intervals \
                   9969: on left y-scale as well as proportions of time spent in each live state \
                   9970: (with confidence intervals) on right y-scale 0 to 100%%.\
                   9971:  If popbased=1 the smooth (due to the model)                           \
1.128     brouard  9972: true period expectancies (those weighted with period prevalences are also\
                   9973:  drawn in addition to the population based expectancies computed using\
1.314     brouard  9974:  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);
                   9975:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   9976:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  9977:      /* } /\* end i1 *\/ */
1.241     brouard  9978:   }/* End nres */
1.222     brouard  9979:    fprintf(fichtm,"</ul>");
                   9980:    fflush(fichtm);
1.126     brouard  9981: }
                   9982: 
                   9983: /******************* Gnuplot file **************/
1.296     brouard  9984: 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  9985: 
1.354     brouard  9986:   char dirfileres[256],optfileres[256];
                   9987:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  9988:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,kf=0,kvar=0,kk=0,ipos=0,iposold=0,ij=0, ijp=0, l=0;
1.211     brouard  9989:   int lv=0, vlv=0, kl=0;
1.130     brouard  9990:   int ng=0;
1.201     brouard  9991:   int vpopbased;
1.223     brouard  9992:   int ioffset; /* variable offset for columns */
1.270     brouard  9993:   int iyearc=1; /* variable column for year of projection  */
                   9994:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  9995:   int nres=0; /* Index of resultline */
1.266     brouard  9996:   int istart=1; /* For starting graphs in projections */
1.219     brouard  9997: 
1.126     brouard  9998: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   9999: /*     printf("Problem with file %s",optionfilegnuplot); */
                   10000: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   10001: /*   } */
                   10002: 
                   10003:   /*#ifdef windows */
                   10004:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  10005:   /*#endif */
1.225     brouard  10006:   m=pow(2,cptcoveff);
1.126     brouard  10007: 
1.274     brouard  10008:   /* diagram of the model */
                   10009:   fprintf(ficgp,"\n#Diagram of the model \n");
                   10010:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   10011:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   10012:   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);
                   10013: 
1.343     brouard  10014:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] for [j=1:%d] arrow (%d+1)*10+i from cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.80*(cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0)  ), -0.80*(sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) + yoff ) ls 4\n",nlstate, nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
1.274     brouard  10015:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   10016:   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);
                   10017:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   10018:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   10019:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   10020:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   10021: 
1.202     brouard  10022:   /* Contribution to likelihood */
                   10023:   /* Plot the probability implied in the likelihood */
1.223     brouard  10024:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   10025:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   10026:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   10027:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  10028: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  10029:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   10030: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  10031:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   10032:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10033:   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));
                   10034:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10035:   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));
                   10036:   for (i=1; i<= nlstate ; i ++) {
                   10037:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   10038:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   10039:     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);
                   10040:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   10041:       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);
                   10042:     }
                   10043:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10044:   }
                   10045:   /* 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 */               
                   10046:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10047:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10048:   fprintf(ficgp,"\nset out;unset log\n");
                   10049:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  10050: 
1.343     brouard  10051:   /* Plot the probability implied in the likelihood by covariate value */
                   10052:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   10053:   /* if(debugILK==1){ */
                   10054:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  10055:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   10056:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  10057:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  10058:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  10059:     k=16+nlstate+kf;/*offset because there are 19 columns in the ILK_ file, first cov Vn on col 21 with 4 living states */
1.343     brouard  10060:     for (i=1; i<= nlstate ; i ++) {
                   10061:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10062:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  10063:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10064:        fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
                   10065:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10066:          fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
                   10067:        }
                   10068:       }else{
                   10069:        fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
                   10070:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10071:          fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
                   10072:        }
1.343     brouard  10073:       }
                   10074:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10075:     }
                   10076:   } /* End of each covariate dummy */
                   10077:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   10078:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   10079:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   10080:      *  varying                   1     2                                 3       4        5
                   10081:      *  ncovv                     1     2                                3 4     5 6      7 8
                   10082:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   10083:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   10084:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   10085:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   10086:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   10087:      */
                   10088:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   10089:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   10090:     /* printf("DebugILK ficgp ncovv=%d, kvar=TvarVV[ncovv]=%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   10091:     if(ipos!=iposold){ /* Not a product or first of a product */
                   10092:       /* printf(" %d",ipos); */
                   10093:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   10094:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   10095:       kk++; /* Position of the ncovv column in ILK_ */
                   10096:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   10097:       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   10098:        for (i=1; i<= nlstate ; i ++) {
                   10099:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10100:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   10101: 
1.348     brouard  10102:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  10103:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10104:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   10105:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
                   10106:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10107:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
                   10108:            }
                   10109:          }else{
                   10110:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   10111:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
                   10112:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10113:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
                   10114:            }
                   10115:          }
                   10116:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10117:        }
                   10118:       }/* End if dummy varying */
                   10119:     }else{ /*Product */
                   10120:       /* printf("*"); */
                   10121:       /* fprintf(ficresilk,"*"); */
                   10122:     }
                   10123:     iposold=ipos;
                   10124:   } /* For each time varying covariate */
                   10125:   /* } /\* debugILK==1 *\/ */
                   10126:   /* 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 */               
                   10127:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10128:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10129:   fprintf(ficgp,"\nset out;unset log\n");
                   10130:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   10131: 
                   10132: 
                   10133:   
1.126     brouard  10134:   strcpy(dirfileres,optionfilefiname);
                   10135:   strcpy(optfileres,"vpl");
1.223     brouard  10136:   /* 1eme*/
1.238     brouard  10137:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  10138:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  10139:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10140:        k1=TKresult[nres];
1.338     brouard  10141:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  10142:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  10143:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10144:        /*   continue; */
1.238     brouard  10145:        /* We are interested in selected combination by the resultline */
1.246     brouard  10146:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  10147:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  10148:        strcpy(gplotlabel,"(");
1.337     brouard  10149:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10150:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10151:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10152: 
                   10153:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   10154:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   10155:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10156:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10157:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10158:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10159:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   10160:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   10161:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   10162:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10163:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10164:        /* } */
                   10165:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10166:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   10167:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10168:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  10169:        }
                   10170:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  10171:        /* printf("\n#\n"); */
1.238     brouard  10172:        fprintf(ficgp,"\n#\n");
                   10173:        if(invalidvarcomb[k1]){
1.260     brouard  10174:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  10175:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10176:          continue;
                   10177:        }
1.235     brouard  10178:       
1.241     brouard  10179:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   10180:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  10181:        /* 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  10182:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  10183:        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);
                   10184:        /* 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); */
                   10185:       /* k1-1 error should be nres-1*/
1.238     brouard  10186:        for (i=1; i<= nlstate ; i ++) {
                   10187:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10188:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   10189:        }
1.288     brouard  10190:        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  10191:        for (i=1; i<= nlstate ; i ++) {
                   10192:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10193:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10194:        } 
1.260     brouard  10195:        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  10196:        for (i=1; i<= nlstate ; i ++) {
                   10197:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10198:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10199:        }  
1.265     brouard  10200:        /* 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)); */
                   10201:        
                   10202:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   10203:         if(cptcoveff ==0){
1.271     brouard  10204:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  10205:        }else{
                   10206:          kl=0;
                   10207:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10208:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10209:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  10210:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10211:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10212:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10213:            vlv= nbcode[Tvaraff[k]][lv];
                   10214:            kl++;
                   10215:            /* 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 *\/ */
                   10216:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10217:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10218:            /* ''  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*/
                   10219:            if(k==cptcoveff){
                   10220:              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], \
                   10221:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   10222:            }else{
                   10223:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   10224:              kl++;
                   10225:            }
                   10226:          } /* end covariate */
                   10227:        } /* end if no covariate */
                   10228: 
1.296     brouard  10229:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  10230:          /* 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  10231:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  10232:          if(cptcoveff ==0){
1.245     brouard  10233:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  10234:          }else{
                   10235:            kl=0;
                   10236:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10237:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10238:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  10239:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10240:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10241:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10242:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   10243:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  10244:              kl++;
1.238     brouard  10245:              /* 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 *\/ */
                   10246:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10247:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10248:              /* ''  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*/
                   10249:              if(k==cptcoveff){
1.245     brouard  10250:                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  10251:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  10252:              }else{
1.332     brouard  10253:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  10254:                kl++;
                   10255:              }
                   10256:            } /* end covariate */
                   10257:          } /* end if no covariate */
1.296     brouard  10258:          if(prevbcast == 1){
1.268     brouard  10259:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   10260:            /* k1-1 error should be nres-1*/
                   10261:            for (i=1; i<= nlstate ; i ++) {
                   10262:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10263:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   10264:            }
1.271     brouard  10265:            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  10266:            for (i=1; i<= nlstate ; i ++) {
                   10267:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10268:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10269:            } 
1.276     brouard  10270:            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  10271:            for (i=1; i<= nlstate ; i ++) {
                   10272:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10273:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10274:            } 
1.274     brouard  10275:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  10276:          } /* end if backprojcast */
1.296     brouard  10277:        } /* end if prevbcast */
1.276     brouard  10278:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   10279:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  10280:       } /* nres */
1.337     brouard  10281:     /* } /\* k1 *\/ */
1.201     brouard  10282:   } /* cpt */
1.235     brouard  10283: 
                   10284:   
1.126     brouard  10285:   /*2 eme*/
1.337     brouard  10286:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  10287:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10288:       k1=TKresult[nres];
1.338     brouard  10289:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10290:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10291:       /*       continue; */
1.238     brouard  10292:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  10293:       strcpy(gplotlabel,"(");
1.337     brouard  10294:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10295:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10296:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10297:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10298:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10299:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10300:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10301:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10302:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10303:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10304:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10305:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10306:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10307:       /* } */
                   10308:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   10309:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10310:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10311:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10312:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  10313:       }
1.264     brouard  10314:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10315:       fprintf(ficgp,"\n#\n");
1.223     brouard  10316:       if(invalidvarcomb[k1]){
                   10317:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10318:        continue;
                   10319:       }
1.219     brouard  10320:                        
1.241     brouard  10321:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  10322:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  10323:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   10324:        if(vpopbased==0){
1.360     brouard  10325:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nunset ytics; unset y2tics; set ytics nomirror; set y2tics 0,10,100;set y2range [0:100];\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  10326:        }else
1.238     brouard  10327:          fprintf(ficgp,"\nreplot ");
1.360     brouard  10328:        for (i=1; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
1.238     brouard  10329:          k=2*i;
1.360     brouard  10330:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased); /* for fixed variables age, popbased, mobilav */
                   10331:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10332:            if (j==i) fprintf(ficgp," %%lf (%%lf)"); /* We want to read e.. i=1,j=1, e.1 i=2,j=2, e.2 i=3,j=3 */
                   10333:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
1.238     brouard  10334:          }   
                   10335:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
1.360     brouard  10336:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1); /* state=i-1=1 to nlstate  */
1.261     brouard  10337:          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  10338:          for (j=1; j<= nlstate+1 ; j ++) {
                   10339:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10340:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10341:          }   
                   10342:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  10343:          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  10344:          for (j=1; j<= nlstate+1 ; j ++) {
                   10345:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10346:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10347:          }   
1.360     brouard  10348:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0,\\\n"); /* ,\\\n added for th percentage graphs */
1.238     brouard  10349:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   10350:        } /* state */
1.360     brouard  10351:        /* again for the percentag spent in state i-1=1 to i-1=nlstate */
                   10352:        for (i=2; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
                   10353:          k=2*i;
                   10354:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d &&  ($4)<=1 && ($4)>=0 ?($4)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased); /* for fixed variables age, popbased, mobilav */
                   10355:          for (j=1; j<= nlstate ; j ++)
                   10356:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10357:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10358:            if (j==i) fprintf(ficgp," %%lf (%%lf)"); /* We want to read e.. i=1,j=1, e.1 i=2,j=2, e.2 i=3,j=3 */
                   10359:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
                   10360:          }   
                   10361:          if (i== 1) fprintf(ficgp,"\" t\"%%TLE\" w l lt %d axis x1y2, \\\n",i); /* Not used */
                   10362:          else fprintf(ficgp,"\" t\"%%LE in state (%d)\" w l lw 2 lt %d axis x1y2, \\\n",i-1,i+1); /* state=i-1=1 to nlstate  */
                   10363:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && ($4-$5*2)<=1 && ($4-$5*2)>=0? ($4-$5*2)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
                   10364:          for (j=1; j<= nlstate ; j ++)
                   10365:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10366:          for (j=1; j<= nlstate+1 ; j ++) {
                   10367:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10368:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10369:          }   
                   10370:          fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,");
                   10371:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && ($4+$5*2)<=1 && ($4+$5*2)>=0 ? ($4+$5*2)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
                   10372:          for (j=1; j<= nlstate ; j ++)
                   10373:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10374:          for (j=1; j<= nlstate+1 ; j ++) {
                   10375:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10376:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10377:          }   
                   10378:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2");
                   10379:          else fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,\\\n");
                   10380:        } /* state for percent */
1.238     brouard  10381:       } /* vpopbased */
1.264     brouard  10382:       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  10383:     } /* end nres */
1.337     brouard  10384:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  10385:        
                   10386:        
                   10387:   /*3eme*/
1.337     brouard  10388:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  10389:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10390:       k1=TKresult[nres];
1.338     brouard  10391:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10392:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10393:       /*       continue; */
1.238     brouard  10394: 
1.332     brouard  10395:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  10396:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  10397:        strcpy(gplotlabel,"(");
1.337     brouard  10398:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10399:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10400:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10401:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10402:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10403:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10404:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10405:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10406:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10407:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10408:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10409:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10410:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10411:        /* } */
                   10412:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10413:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10414:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10415:        }
1.264     brouard  10416:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10417:        fprintf(ficgp,"\n#\n");
                   10418:        if(invalidvarcomb[k1]){
                   10419:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10420:          continue;
                   10421:        }
                   10422:                        
                   10423:        /*       k=2+nlstate*(2*cpt-2); */
                   10424:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  10425:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  10426:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  10427:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  10428: 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  10429:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10430:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10431:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   10432:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10433:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10434:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  10435:                                
1.238     brouard  10436:        */
                   10437:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  10438:          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  10439:          /*    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  10440:                                
1.238     brouard  10441:        } 
1.261     brouard  10442:        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  10443:       }
1.264     brouard  10444:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  10445:     } /* end nres */
1.337     brouard  10446:   /* } /\* end kl 3eme *\/ */
1.126     brouard  10447:   
1.223     brouard  10448:   /* 4eme */
1.201     brouard  10449:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  10450:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  10451:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10452:       k1=TKresult[nres];
1.338     brouard  10453:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10454:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10455:       /*       continue; */
1.238     brouard  10456:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  10457:        strcpy(gplotlabel,"(");
1.337     brouard  10458:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   10459:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10460:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10461:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10462:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10463:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10464:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10465:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10466:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10467:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10468:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10469:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10470:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10471:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10472:        /* } */
                   10473:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10474:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10475:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10476:        }       
1.264     brouard  10477:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10478:        fprintf(ficgp,"\n#\n");
                   10479:        if(invalidvarcomb[k1]){
                   10480:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10481:          continue;
1.223     brouard  10482:        }
1.238     brouard  10483:       
1.241     brouard  10484:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  10485:        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  10486:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10487: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10488:        k=3;
                   10489:        for (i=1; i<= nlstate ; i ++){
                   10490:          if(i==1){
                   10491:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10492:          }else{
                   10493:            fprintf(ficgp,", '' ");
                   10494:          }
                   10495:          l=(nlstate+ndeath)*(i-1)+1;
                   10496:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10497:          for (j=2; j<= nlstate+ndeath ; j ++)
                   10498:            fprintf(ficgp,"+$%d",k+l+j-1);
                   10499:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   10500:        } /* nlstate */
1.264     brouard  10501:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10502:       } /* end cpt state*/ 
                   10503:     } /* end nres */
1.337     brouard  10504:   /* } /\* end covariate k1 *\/   */
1.238     brouard  10505: 
1.220     brouard  10506: /* 5eme */
1.201     brouard  10507:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  10508:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  10509:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10510:       k1=TKresult[nres];
1.338     brouard  10511:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10512:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10513:       /*       continue; */
1.238     brouard  10514:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  10515:        strcpy(gplotlabel,"(");
1.238     brouard  10516:        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  10517:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10518:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10519:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10520:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10521:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10522:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10523:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10524:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10525:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10526:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10527:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10528:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10529:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10530:        /* } */
                   10531:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10532:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10533:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10534:        }       
1.264     brouard  10535:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10536:        fprintf(ficgp,"\n#\n");
                   10537:        if(invalidvarcomb[k1]){
                   10538:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10539:          continue;
                   10540:        }
1.227     brouard  10541:       
1.241     brouard  10542:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  10543:        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  10544:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10545: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10546:        k=3;
                   10547:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10548:          if(j==1)
                   10549:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10550:          else
                   10551:            fprintf(ficgp,", '' ");
                   10552:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10553:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   10554:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   10555:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   10556:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   10557:        } /* nlstate */
                   10558:        fprintf(ficgp,", '' ");
                   10559:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   10560:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10561:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10562:          if(j < nlstate)
                   10563:            fprintf(ficgp,"$%d +",k+l);
                   10564:          else
                   10565:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   10566:        }
1.264     brouard  10567:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10568:       } /* end cpt state*/ 
1.337     brouard  10569:     /* } /\* end covariate *\/   */
1.238     brouard  10570:   } /* end nres */
1.227     brouard  10571:   
1.220     brouard  10572: /* 6eme */
1.202     brouard  10573:   /* CV preval stable (period) for each covariate */
1.337     brouard  10574:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10575:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10576:      k1=TKresult[nres];
1.338     brouard  10577:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10578:      /* if(m != 1 && TKresult[nres]!= k1) */
                   10579:      /*  continue; */
1.255     brouard  10580:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  10581:       strcpy(gplotlabel,"(");      
1.288     brouard  10582:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10583:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10584:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10585:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10586:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10587:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10588:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10589:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10590:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10591:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10592:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10593:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10594:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10595:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10596:       /* } */
                   10597:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10598:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10599:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10600:       }        
1.264     brouard  10601:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10602:       fprintf(ficgp,"\n#\n");
1.223     brouard  10603:       if(invalidvarcomb[k1]){
1.227     brouard  10604:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10605:        continue;
1.223     brouard  10606:       }
1.227     brouard  10607:       
1.241     brouard  10608:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  10609:       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  10610:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10611: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  10612:       k=3; /* Offset */
1.255     brouard  10613:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  10614:        if(i==1)
                   10615:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10616:        else
                   10617:          fprintf(ficgp,", '' ");
1.255     brouard  10618:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  10619:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10620:        for (j=2; j<= nlstate ; j ++)
                   10621:          fprintf(ficgp,"+$%d",k+l+j-1);
                   10622:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  10623:       } /* nlstate */
1.264     brouard  10624:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  10625:     } /* end cpt state*/ 
                   10626:   } /* end covariate */  
1.227     brouard  10627:   
                   10628:   
1.220     brouard  10629: /* 7eme */
1.296     brouard  10630:   if(prevbcast == 1){
1.288     brouard  10631:     /* CV backward prevalence  for each covariate */
1.337     brouard  10632:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10633:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10634:       k1=TKresult[nres];
1.338     brouard  10635:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10636:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10637:       /*       continue; */
1.268     brouard  10638:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  10639:        strcpy(gplotlabel,"(");      
1.288     brouard  10640:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10641:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10642:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10643:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10644:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10645:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10646:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10647:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10648:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10649:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10650:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10651:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10652:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10653:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10654:        /* } */
                   10655:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10656:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10657:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10658:        }       
1.264     brouard  10659:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10660:        fprintf(ficgp,"\n#\n");
                   10661:        if(invalidvarcomb[k1]){
                   10662:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10663:          continue;
                   10664:        }
                   10665:        
1.241     brouard  10666:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  10667:        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  10668:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10669: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  10670:        k=3; /* Offset */
1.268     brouard  10671:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  10672:          if(i==1)
                   10673:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   10674:          else
                   10675:            fprintf(ficgp,", '' ");
                   10676:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  10677:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  10678:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   10679:          /* 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  10680:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  10681:          /* for (j=2; j<= nlstate ; j ++) */
                   10682:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   10683:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  10684:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  10685:        } /* nlstate */
1.264     brouard  10686:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  10687:       } /* end cpt state*/ 
                   10688:     } /* end covariate */  
1.296     brouard  10689:   } /* End if prevbcast */
1.218     brouard  10690:   
1.223     brouard  10691:   /* 8eme */
1.218     brouard  10692:   if(prevfcast==1){
1.288     brouard  10693:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  10694:     
1.337     brouard  10695:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10696:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10697:       k1=TKresult[nres];
1.338     brouard  10698:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10699:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10700:       /*       continue; */
1.211     brouard  10701:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  10702:        strcpy(gplotlabel,"(");      
1.288     brouard  10703:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10704:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10705:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10706:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10707:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10708:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10709:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10710:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10711:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10712:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10713:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10714:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10715:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10716:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10717:        /* } */
                   10718:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10719:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10720:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10721:        }       
1.264     brouard  10722:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10723:        fprintf(ficgp,"\n#\n");
                   10724:        if(invalidvarcomb[k1]){
                   10725:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10726:          continue;
                   10727:        }
                   10728:        
                   10729:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  10730:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  10731:        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  10732:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  10733: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  10734: 
                   10735:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10736:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10737:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10738:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  10739:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10740:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10741:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10742:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  10743:          if(i==istart){
1.227     brouard  10744:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   10745:          }else{
                   10746:            fprintf(ficgp,",\\\n '' ");
                   10747:          }
                   10748:          if(cptcoveff ==0){ /* No covariate */
                   10749:            ioffset=2; /* Age is in 2 */
                   10750:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10751:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10752:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10753:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10754:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  10755:            if(i==nlstate+1){
1.270     brouard  10756:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  10757:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10758:              fprintf(ficgp,",\\\n '' ");
                   10759:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10760:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  10761:                     offyear,                           \
1.268     brouard  10762:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  10763:            }else
1.227     brouard  10764:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   10765:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10766:          }else{ /* more than 2 covariates */
1.270     brouard  10767:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10768:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10769:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10770:            iyearc=ioffset-1;
                   10771:            iagec=ioffset;
1.227     brouard  10772:            fprintf(ficgp," u %d:(",ioffset); 
                   10773:            kl=0;
                   10774:            strcpy(gplotcondition,"(");
1.351     brouard  10775:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  10776:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  10777:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10778:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10779:              lv=Tvresult[nres][k];
                   10780:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  10781:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10782:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10783:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10784:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  10785:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  10786:              kl++;
1.351     brouard  10787:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10788:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  10789:              kl++;
1.351     brouard  10790:              if(k <cptcovs && cptcovs>1)
1.227     brouard  10791:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10792:            }
                   10793:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10794:            /* 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 *\/ */
                   10795:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10796:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10797:            /* ''  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*/
                   10798:            if(i==nlstate+1){
1.270     brouard  10799:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   10800:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  10801:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10802:              fprintf(ficgp," u %d:(",iagec); 
                   10803:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   10804:                      iyearc, iagec, offyear,                           \
                   10805:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  10806: /*  '' 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  10807:            }else{
                   10808:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   10809:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10810:            }
                   10811:          } /* end if covariate */
                   10812:        } /* nlstate */
1.264     brouard  10813:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  10814:       } /* end cpt state*/
                   10815:     } /* end covariate */
                   10816:   } /* End if prevfcast */
1.227     brouard  10817:   
1.296     brouard  10818:   if(prevbcast==1){
1.268     brouard  10819:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   10820:     
1.337     brouard  10821:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  10822:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10823:      k1=TKresult[nres];
1.338     brouard  10824:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10825:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10826:        /*      continue; */
1.268     brouard  10827:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   10828:        strcpy(gplotlabel,"(");      
                   10829:        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  10830:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10831:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10832:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10833:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10834:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10835:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10836:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10837:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10838:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10839:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10840:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10841:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10842:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10843:        /* } */
                   10844:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10845:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10846:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  10847:        }       
                   10848:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   10849:        fprintf(ficgp,"\n#\n");
                   10850:        if(invalidvarcomb[k1]){
                   10851:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10852:          continue;
                   10853:        }
                   10854:        
                   10855:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   10856:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   10857:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   10858:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   10859: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10860: 
                   10861:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10862:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10863:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10864:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   10865:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10866:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10867:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10868:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10869:          if(i==istart){
                   10870:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   10871:          }else{
                   10872:            fprintf(ficgp,",\\\n '' ");
                   10873:          }
1.351     brouard  10874:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   10875:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  10876:            ioffset=2; /* Age is in 2 */
                   10877:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10878:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10879:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10880:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10881:            fprintf(ficgp," u %d:(", ioffset); 
                   10882:            if(i==nlstate+1){
1.270     brouard  10883:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  10884:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10885:              fprintf(ficgp,",\\\n '' ");
                   10886:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10887:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  10888:                     offbyear,                          \
                   10889:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   10890:            }else
                   10891:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   10892:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   10893:          }else{ /* more than 2 covariates */
1.270     brouard  10894:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10895:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10896:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10897:            iyearc=ioffset-1;
                   10898:            iagec=ioffset;
1.268     brouard  10899:            fprintf(ficgp," u %d:(",ioffset); 
                   10900:            kl=0;
                   10901:            strcpy(gplotcondition,"(");
1.337     brouard  10902:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  10903:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  10904:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   10905:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10906:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10907:                lv=Tvresult[nres][k];
                   10908:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   10909:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10910:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10911:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10912:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   10913:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10914:                kl++;
                   10915:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10916:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   10917:                kl++;
1.338     brouard  10918:                if(k <cptcovs && cptcovs>1)
1.337     brouard  10919:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10920:              }
1.268     brouard  10921:            }
                   10922:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10923:            /* 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 *\/ */
                   10924:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10925:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10926:            /* ''  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*/
                   10927:            if(i==nlstate+1){
1.270     brouard  10928:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   10929:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  10930:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10931:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  10932:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  10933:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   10934:                      iyearc,iagec,offbyear,                            \
                   10935:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  10936: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   10937:            }else{
                   10938:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   10939:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   10940:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   10941:            }
                   10942:          } /* end if covariate */
                   10943:        } /* nlstate */
                   10944:        fprintf(ficgp,"\nset out; unset label;\n");
                   10945:       } /* end cpt state*/
                   10946:     } /* end covariate */
1.296     brouard  10947:   } /* End if prevbcast */
1.268     brouard  10948:   
1.227     brouard  10949:   
1.238     brouard  10950:   /* 9eme writing MLE parameters */
                   10951:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  10952:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  10953:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  10954:     for(k=1; k <=(nlstate+ndeath); k++){
                   10955:       if (k != i) {
1.227     brouard  10956:        fprintf(ficgp,"#   current state %d\n",k);
                   10957:        for(j=1; j <=ncovmodel; j++){
                   10958:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   10959:          jk++; 
                   10960:        }
                   10961:        fprintf(ficgp,"\n");
1.126     brouard  10962:       }
                   10963:     }
1.223     brouard  10964:   }
1.187     brouard  10965:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  10966:   
1.145     brouard  10967:   /*goto avoid;*/
1.238     brouard  10968:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   10969:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  10970:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   10971:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   10972:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   10973:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   10974:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10975:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10976:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10977:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10978:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   10979:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10980:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   10981:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   10982:   fprintf(ficgp,"#\n");
1.223     brouard  10983:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  10984:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  10985:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  10986:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  10987:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   10988:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  10989:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  10990:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10991:      /* k1=nres; */
1.338     brouard  10992:       k1=TKresult[nres];
                   10993:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10994:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  10995:       strcpy(gplotlabel,"(");
1.276     brouard  10996:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  10997:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   10998:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   10999:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   11000:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   11001:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   11002:       }
                   11003:       /* if(m != 1 && TKresult[nres]!= k1) */
                   11004:       /*       continue; */
                   11005:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   11006:       /* strcpy(gplotlabel,"("); */
                   11007:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   11008:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   11009:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   11010:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   11011:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   11012:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   11013:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   11014:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   11015:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   11016:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   11017:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   11018:       /* } */
                   11019:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11020:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11021:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11022:       /* }      */
1.264     brouard  11023:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  11024:       fprintf(ficgp,"\n#\n");
1.264     brouard  11025:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  11026:       fprintf(ficgp,"\nset key outside ");
                   11027:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   11028:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  11029:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   11030:       if (ng==1){
                   11031:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   11032:        fprintf(ficgp,"\nunset log y");
                   11033:       }else if (ng==2){
                   11034:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   11035:        fprintf(ficgp,"\nset log y");
                   11036:       }else if (ng==3){
                   11037:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   11038:        fprintf(ficgp,"\nset log y");
                   11039:       }else
                   11040:        fprintf(ficgp,"\nunset title ");
                   11041:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   11042:       i=1;
                   11043:       for(k2=1; k2<=nlstate; k2++) {
                   11044:        k3=i;
                   11045:        for(k=1; k<=(nlstate+ndeath); k++) {
                   11046:          if (k != k2){
                   11047:            switch( ng) {
                   11048:            case 1:
                   11049:              if(nagesqr==0)
                   11050:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   11051:              else /* nagesqr =1 */
                   11052:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11053:              break;
                   11054:            case 2: /* ng=2 */
                   11055:              if(nagesqr==0)
                   11056:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   11057:              else /* nagesqr =1 */
                   11058:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11059:              break;
                   11060:            case 3:
                   11061:              if(nagesqr==0)
                   11062:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   11063:              else /* nagesqr =1 */
                   11064:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   11065:              break;
                   11066:            }
                   11067:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  11068:            ijp=1; /* product no age */
                   11069:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   11070:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  11071:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  11072:              switch(Typevar[j]){
                   11073:              case 1:
                   11074:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11075:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   11076:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11077:                      if(DummyV[j]==0){/* Bug valgrind */
                   11078:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   11079:                      }else{ /* quantitative */
                   11080:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11081:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11082:                      }
                   11083:                      ij++;
1.268     brouard  11084:                    }
1.237     brouard  11085:                  }
1.329     brouard  11086:                }
                   11087:                break;
                   11088:              case 2:
                   11089:                if(cptcovprod >0){
                   11090:                  if(j==Tprod[ijp]) { /* */ 
                   11091:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11092:                    if(ijp <=cptcovprod) { /* Product */
                   11093:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11094:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11095:                          /* 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)]); */
                   11096:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11097:                        }else{ /* Vn is dummy and Vm is quanti */
                   11098:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11099:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11100:                        }
                   11101:                      }else{ /* Vn*Vm Vn is quanti */
                   11102:                        if(DummyV[Tvard[ijp][2]]==0){
                   11103:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11104:                        }else{ /* Both quanti */
                   11105:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11106:                        }
1.268     brouard  11107:                      }
1.329     brouard  11108:                      ijp++;
1.237     brouard  11109:                    }
1.329     brouard  11110:                  } /* end Tprod */
                   11111:                }
                   11112:                break;
1.349     brouard  11113:              case 3:
                   11114:                if(cptcovdageprod >0){
                   11115:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   11116:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  11117:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   11118:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11119:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11120:                          /* 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)]); */
                   11121:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11122:                        }else{ /* Vn is dummy and Vm is quanti */
                   11123:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  11124:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11125:                        }
1.350     brouard  11126:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  11127:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  11128:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  11129:                        }else{ /* Both quanti */
1.350     brouard  11130:                          fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11131:                        }
                   11132:                      }
                   11133:                      ijp++;
                   11134:                    }
                   11135:                    /* } */ /* end Tprod */
                   11136:                }
                   11137:                break;
1.329     brouard  11138:              case 0:
                   11139:                /* simple covariate */
1.264     brouard  11140:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  11141:                if(Dummy[j]==0){
                   11142:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   11143:                }else{ /* quantitative */
                   11144:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  11145:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  11146:                }
1.329     brouard  11147:               /* end simple */
                   11148:                break;
                   11149:              default:
                   11150:                break;
                   11151:              } /* end switch */
1.237     brouard  11152:            } /* end j */
1.329     brouard  11153:          }else{ /* k=k2 */
                   11154:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   11155:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   11156:            }else
                   11157:              i=i-ncovmodel;
1.223     brouard  11158:          }
1.227     brouard  11159:          
1.223     brouard  11160:          if(ng != 1){
                   11161:            fprintf(ficgp,")/(1");
1.227     brouard  11162:            
1.264     brouard  11163:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  11164:              if(nagesqr==0)
1.264     brouard  11165:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  11166:              else /* nagesqr =1 */
1.264     brouard  11167:                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  11168:               
1.223     brouard  11169:              ij=1;
1.329     brouard  11170:              ijp=1;
                   11171:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   11172:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   11173:                switch(Typevar[j]){
                   11174:                case 1:
                   11175:                  if(cptcovage >0){ 
                   11176:                    if(j==Tage[ij]) { /* Bug valgrind */
                   11177:                      if(ij <=cptcovage) { /* Bug valgrind */
                   11178:                        if(DummyV[j]==0){/* Bug valgrind */
                   11179:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   11180:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   11181:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   11182:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   11183:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11184:                        }else{ /* quantitative */
                   11185:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11186:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11187:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11188:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11189:                        }
                   11190:                        ij++;
                   11191:                      }
                   11192:                    }
                   11193:                  }
                   11194:                  break;
                   11195:                case 2:
                   11196:                  if(cptcovprod >0){
                   11197:                    if(j==Tprod[ijp]) { /* */ 
                   11198:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11199:                      if(ijp <=cptcovprod) { /* Product */
                   11200:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11201:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11202:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
                   11203:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11204:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11205:                          }else{ /* Vn is dummy and Vm is quanti */
                   11206:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11207:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11208:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11209:                          }
                   11210:                        }else{ /* Vn*Vm Vn is quanti */
                   11211:                          if(DummyV[Tvard[ijp][2]]==0){
                   11212:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11213:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11214:                          }else{ /* Both quanti */
                   11215:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11216:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11217:                          } 
                   11218:                        }
                   11219:                        ijp++;
                   11220:                      }
                   11221:                    } /* end Tprod */
                   11222:                  } /* end if */
                   11223:                  break;
1.349     brouard  11224:                case 3:
                   11225:                  if(cptcovdageprod >0){
                   11226:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   11227:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11228:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  11229:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11230:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11231:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
1.350     brouard  11232:                            fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11233:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11234:                          }else{ /* Vn is dummy and Vm is quanti */
                   11235:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  11236:                            fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11237:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11238:                          }
                   11239:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  11240:                          if(DummyV[Tvardk[ijp][2]]==0){
                   11241:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  11242:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11243:                          }else{ /* Both quanti */
1.350     brouard  11244:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11245:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11246:                          } 
                   11247:                        }
                   11248:                        ijp++;
                   11249:                      }
                   11250:                    /* } /\* end Tprod *\/ */
                   11251:                  } /* end if */
                   11252:                  break;
1.329     brouard  11253:                case 0: 
                   11254:                  /* simple covariate */
                   11255:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   11256:                  if(Dummy[j]==0){
                   11257:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11258:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   11259:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11260:                  }else{ /* quantitative */
                   11261:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   11262:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   11263:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11264:                  }
                   11265:                  /* end simple */
                   11266:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   11267:                  break;
                   11268:                default:
                   11269:                  break;
                   11270:                } /* end switch */
1.223     brouard  11271:              }
                   11272:              fprintf(ficgp,")");
                   11273:            }
                   11274:            fprintf(ficgp,")");
                   11275:            if(ng ==2)
1.276     brouard  11276:              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  11277:            else /* ng= 3 */
1.276     brouard  11278:              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  11279:           }else{ /* end ng <> 1 */
1.223     brouard  11280:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  11281:              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  11282:          }
                   11283:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   11284:            fprintf(ficgp,",");
                   11285:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   11286:            fprintf(ficgp,",");
                   11287:          i=i+ncovmodel;
                   11288:        } /* end k */
                   11289:       } /* end k2 */
1.276     brouard  11290:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   11291:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  11292:     } /* end resultline */
1.223     brouard  11293:   } /* end ng */
                   11294:   /* avoid: */
                   11295:   fflush(ficgp); 
1.126     brouard  11296: }  /* end gnuplot */
                   11297: 
                   11298: 
                   11299: /*************** Moving average **************/
1.219     brouard  11300: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  11301:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  11302:    
1.222     brouard  11303:    int i, cpt, cptcod;
                   11304:    int modcovmax =1;
                   11305:    int mobilavrange, mob;
                   11306:    int iage=0;
1.288     brouard  11307:    int firstA1=0, firstA2=0;
1.222     brouard  11308: 
1.266     brouard  11309:    double sum=0., sumr=0.;
1.222     brouard  11310:    double age;
1.266     brouard  11311:    double *sumnewp, *sumnewm, *sumnewmr;
                   11312:    double *agemingood, *agemaxgood; 
                   11313:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  11314:   
                   11315:   
1.278     brouard  11316:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   11317:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  11318: 
                   11319:    sumnewp = vector(1,ncovcombmax);
                   11320:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  11321:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  11322:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  11323:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  11324:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  11325:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  11326: 
                   11327:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  11328:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  11329:      sumnewp[cptcod]=0.;
1.266     brouard  11330:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   11331:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  11332:    }
                   11333:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   11334:   
1.266     brouard  11335:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   11336:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  11337:      else mobilavrange=mobilav;
                   11338:      for (age=bage; age<=fage; age++)
                   11339:        for (i=1; i<=nlstate;i++)
                   11340:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   11341:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11342:      /* We keep the original values on the extreme ages bage, fage and for 
                   11343:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   11344:        we use a 5 terms etc. until the borders are no more concerned. 
                   11345:      */ 
                   11346:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   11347:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  11348:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   11349:           sumnewm[cptcod]=0.;
                   11350:           for (i=1; i<=nlstate;i++){
1.222     brouard  11351:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   11352:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   11353:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   11354:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   11355:             }
                   11356:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  11357:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11358:           } /* end i */
                   11359:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   11360:         } /* end cptcod */
1.222     brouard  11361:        }/* end age */
                   11362:      }/* end mob */
1.266     brouard  11363:    }else{
                   11364:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  11365:      return -1;
1.266     brouard  11366:    }
                   11367: 
                   11368:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  11369:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   11370:      if(invalidvarcomb[cptcod]){
                   11371:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   11372:        continue;
                   11373:      }
1.219     brouard  11374: 
1.266     brouard  11375:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   11376:        sumnewm[cptcod]=0.;
                   11377:        sumnewmr[cptcod]=0.;
                   11378:        for (i=1; i<=nlstate;i++){
                   11379:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11380:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11381:        }
                   11382:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11383:         agemingoodr[cptcod]=age;
                   11384:        }
                   11385:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11386:           agemingood[cptcod]=age;
                   11387:        }
                   11388:      } /* age */
                   11389:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  11390:        sumnewm[cptcod]=0.;
1.266     brouard  11391:        sumnewmr[cptcod]=0.;
1.222     brouard  11392:        for (i=1; i<=nlstate;i++){
                   11393:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11394:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11395:        }
                   11396:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11397:         agemaxgoodr[cptcod]=age;
1.222     brouard  11398:        }
                   11399:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  11400:         agemaxgood[cptcod]=age;
                   11401:        }
                   11402:      } /* age */
                   11403:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   11404:      /* but they will change */
1.288     brouard  11405:      firstA1=0;firstA2=0;
1.266     brouard  11406:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   11407:        sumnewm[cptcod]=0.;
                   11408:        sumnewmr[cptcod]=0.;
                   11409:        for (i=1; i<=nlstate;i++){
                   11410:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11411:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11412:        }
                   11413:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11414:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11415:           agemaxgoodr[cptcod]=age;  /* age min */
                   11416:           for (i=1; i<=nlstate;i++)
                   11417:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11418:         }else{ /* bad we change the value with the values of good ages */
                   11419:           for (i=1; i<=nlstate;i++){
                   11420:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   11421:           } /* i */
                   11422:         } /* end bad */
                   11423:        }else{
                   11424:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11425:           agemaxgood[cptcod]=age;
                   11426:         }else{ /* bad we change the value with the values of good ages */
                   11427:           for (i=1; i<=nlstate;i++){
                   11428:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   11429:           } /* i */
                   11430:         } /* end bad */
                   11431:        }/* end else */
                   11432:        sum=0.;sumr=0.;
                   11433:        for (i=1; i<=nlstate;i++){
                   11434:         sum+=mobaverage[(int)age][i][cptcod];
                   11435:         sumr+=probs[(int)age][i][cptcod];
                   11436:        }
                   11437:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  11438:         if(!firstA1){
                   11439:           firstA1=1;
                   11440:           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);
                   11441:         }
                   11442:         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  11443:        } /* end bad */
                   11444:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11445:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  11446:         if(!firstA2){
                   11447:           firstA2=1;
                   11448:           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);
                   11449:         }
                   11450:         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  11451:        } /* end bad */
                   11452:      }/* age */
1.266     brouard  11453: 
                   11454:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  11455:        sumnewm[cptcod]=0.;
1.266     brouard  11456:        sumnewmr[cptcod]=0.;
1.222     brouard  11457:        for (i=1; i<=nlstate;i++){
                   11458:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11459:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11460:        } 
                   11461:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11462:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   11463:           agemingoodr[cptcod]=age;
                   11464:           for (i=1; i<=nlstate;i++)
                   11465:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11466:         }else{ /* bad we change the value with the values of good ages */
                   11467:           for (i=1; i<=nlstate;i++){
                   11468:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   11469:           } /* i */
                   11470:         } /* end bad */
                   11471:        }else{
                   11472:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11473:           agemingood[cptcod]=age;
                   11474:         }else{ /* bad */
                   11475:           for (i=1; i<=nlstate;i++){
                   11476:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   11477:           } /* i */
                   11478:         } /* end bad */
                   11479:        }/* end else */
                   11480:        sum=0.;sumr=0.;
                   11481:        for (i=1; i<=nlstate;i++){
                   11482:         sum+=mobaverage[(int)age][i][cptcod];
                   11483:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  11484:        }
1.266     brouard  11485:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  11486:         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  11487:        } /* end bad */
                   11488:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11489:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  11490:         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  11491:        } /* end bad */
                   11492:      }/* age */
1.266     brouard  11493: 
1.222     brouard  11494:                
                   11495:      for (age=bage; age<=fage; age++){
1.235     brouard  11496:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  11497:        sumnewp[cptcod]=0.;
                   11498:        sumnewm[cptcod]=0.;
                   11499:        for (i=1; i<=nlstate;i++){
                   11500:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   11501:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11502:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   11503:        }
                   11504:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   11505:      }
                   11506:      /* printf("\n"); */
                   11507:      /* } */
1.266     brouard  11508: 
1.222     brouard  11509:      /* brutal averaging */
1.266     brouard  11510:      /* for (i=1; i<=nlstate;i++){ */
                   11511:      /*   for (age=1; age<=bage; age++){ */
                   11512:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   11513:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11514:      /*   }     */
                   11515:      /*   for (age=fage; age<=AGESUP; age++){ */
                   11516:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   11517:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11518:      /*   } */
                   11519:      /* } /\* end i status *\/ */
                   11520:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   11521:      /*   for (age=1; age<=AGESUP; age++){ */
                   11522:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   11523:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   11524:      /*   } */
                   11525:      /* } */
1.222     brouard  11526:    }/* end cptcod */
1.266     brouard  11527:    free_vector(agemaxgoodr,1, ncovcombmax);
                   11528:    free_vector(agemaxgood,1, ncovcombmax);
                   11529:    free_vector(agemingood,1, ncovcombmax);
                   11530:    free_vector(agemingoodr,1, ncovcombmax);
                   11531:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  11532:    free_vector(sumnewm,1, ncovcombmax);
                   11533:    free_vector(sumnewp,1, ncovcombmax);
                   11534:    return 0;
                   11535:  }/* End movingaverage */
1.218     brouard  11536:  
1.126     brouard  11537: 
1.296     brouard  11538:  
1.126     brouard  11539: /************** Forecasting ******************/
1.296     brouard  11540: /* 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)*/
                   11541: 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){
                   11542:   /* dateintemean, mean date of interviews
                   11543:      dateprojd, year, month, day of starting projection 
                   11544:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  11545:      agemin, agemax range of age
                   11546:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   11547:   */
1.296     brouard  11548:   /* double anprojd, mprojd, jprojd; */
                   11549:   /* double anprojf, mprojf, jprojf; */
1.359     brouard  11550:   int yearp, stepsize, hstepm, nhstepm, j, k, i, h,  nres=0;
1.126     brouard  11551:   double agec; /* generic age */
1.359     brouard  11552:   double agelim, ppij;
                   11553:   /*double *popcount;*/
1.126     brouard  11554:   double ***p3mat;
1.218     brouard  11555:   /* double ***mobaverage; */
1.126     brouard  11556:   char fileresf[FILENAMELENGTH];
                   11557: 
                   11558:   agelim=AGESUP;
1.211     brouard  11559:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11560:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11561:      We still use firstpass and lastpass as another selection.
                   11562:   */
1.214     brouard  11563:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11564:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  11565:  
1.201     brouard  11566:   strcpy(fileresf,"F_"); 
                   11567:   strcat(fileresf,fileresu);
1.126     brouard  11568:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   11569:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   11570:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   11571:   }
1.235     brouard  11572:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   11573:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  11574: 
1.225     brouard  11575:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  11576: 
                   11577: 
                   11578:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11579:   if (stepm<=12) stepsize=1;
                   11580:   if(estepm < stepm){
                   11581:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11582:   }
1.270     brouard  11583:   else{
                   11584:     hstepm=estepm;   
                   11585:   }
                   11586:   if(estepm > stepm){ /* Yes every two year */
                   11587:     stepsize=2;
                   11588:   }
1.296     brouard  11589:   hstepm=hstepm/stepm;
1.126     brouard  11590: 
1.296     brouard  11591:   
                   11592:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11593:   /*                              fractional in yp1 *\/ */
                   11594:   /* aintmean=yp; */
                   11595:   /* yp2=modf((yp1*12),&yp); */
                   11596:   /* mintmean=yp; */
                   11597:   /* yp1=modf((yp2*30.5),&yp); */
                   11598:   /* jintmean=yp; */
                   11599:   /* if(jintmean==0) jintmean=1; */
                   11600:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  11601: 
1.296     brouard  11602: 
                   11603:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   11604:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   11605:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  11606:   /* i1=pow(2,cptcoveff); */
                   11607:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  11608:   
1.296     brouard  11609:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  11610:   
                   11611:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  11612:   
1.126     brouard  11613: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  11614:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11615:     k=TKresult[nres];
                   11616:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11617:     /*  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) *\/ */
                   11618:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11619:     /*   continue; */
                   11620:     /* if(invalidvarcomb[k]){ */
                   11621:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11622:     /*   continue; */
                   11623:     /* } */
1.227     brouard  11624:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  11625:     for(j=1;j<=cptcovs;j++){
                   11626:       /* for(j=1;j<=cptcoveff;j++) { */
                   11627:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   11628:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11629:     /* } */
                   11630:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11631:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11632:     /* } */
                   11633:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  11634:     }
1.351     brouard  11635:  
1.227     brouard  11636:     fprintf(ficresf," yearproj age");
                   11637:     for(j=1; j<=nlstate+ndeath;j++){ 
                   11638:       for(i=1; i<=nlstate;i++)               
                   11639:        fprintf(ficresf," p%d%d",i,j);
                   11640:       fprintf(ficresf," wp.%d",j);
                   11641:     }
1.296     brouard  11642:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  11643:       fprintf(ficresf,"\n");
1.296     brouard  11644:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  11645:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   11646:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  11647:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   11648:        nhstepm = nhstepm/hstepm; 
                   11649:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11650:        oldm=oldms;savm=savms;
1.268     brouard  11651:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  11652:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  11653:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  11654:        for (h=0; h<=nhstepm; h++){
                   11655:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  11656:            break;
                   11657:          }
                   11658:        }
                   11659:        fprintf(ficresf,"\n");
1.351     brouard  11660:        /* for(j=1;j<=cptcoveff;j++)  */
                   11661:        for(j=1;j<=cptcovs;j++) 
                   11662:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  11663:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  11664:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  11665:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  11666:        
                   11667:        for(j=1; j<=nlstate+ndeath;j++) {
                   11668:          ppij=0.;
                   11669:          for(i=1; i<=nlstate;i++) {
1.278     brouard  11670:            if (mobilav>=1)
                   11671:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   11672:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   11673:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   11674:            }
1.268     brouard  11675:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   11676:          } /* end i */
                   11677:          fprintf(ficresf," %.3f", ppij);
                   11678:        }/* end j */
1.227     brouard  11679:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11680:       } /* end agec */
1.266     brouard  11681:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   11682:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  11683:     } /* end yearp */
                   11684:   } /* end  k */
1.219     brouard  11685:        
1.126     brouard  11686:   fclose(ficresf);
1.215     brouard  11687:   printf("End of Computing forecasting \n");
                   11688:   fprintf(ficlog,"End of Computing forecasting\n");
                   11689: 
1.126     brouard  11690: }
                   11691: 
1.269     brouard  11692: /************** Back Forecasting ******************/
1.296     brouard  11693:  /* 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){ */
                   11694:  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){
                   11695:   /* back1, year, month, day of starting backprojection
1.267     brouard  11696:      agemin, agemax range of age
                   11697:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  11698:      anback2 year of end of backprojection (same day and month as back1).
                   11699:      prevacurrent and prev are prevalences.
1.267     brouard  11700:   */
1.359     brouard  11701:   int yearp, stepsize, hstepm, nhstepm, j, k,  i, h, nres=0;
1.267     brouard  11702:   double agec; /* generic age */
1.359     brouard  11703:   double agelim, ppij, ppi; /* ,jintmean,mintmean,aintmean;*/
                   11704:   /*double *popcount;*/
1.267     brouard  11705:   double ***p3mat;
                   11706:   /* double ***mobaverage; */
                   11707:   char fileresfb[FILENAMELENGTH];
                   11708:  
1.268     brouard  11709:   agelim=AGEINF;
1.267     brouard  11710:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11711:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11712:      We still use firstpass and lastpass as another selection.
                   11713:   */
                   11714:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11715:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   11716: 
                   11717:   /*Do we need to compute prevalence again?*/
                   11718: 
                   11719:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11720:   
                   11721:   strcpy(fileresfb,"FB_");
                   11722:   strcat(fileresfb,fileresu);
                   11723:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   11724:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   11725:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   11726:   }
                   11727:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11728:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11729:   
                   11730:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   11731:   
                   11732:    
                   11733:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11734:   if (stepm<=12) stepsize=1;
                   11735:   if(estepm < stepm){
                   11736:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11737:   }
1.270     brouard  11738:   else{
                   11739:     hstepm=estepm;   
                   11740:   }
                   11741:   if(estepm >= stepm){ /* Yes every two year */
                   11742:     stepsize=2;
                   11743:   }
1.267     brouard  11744:   
                   11745:   hstepm=hstepm/stepm;
1.296     brouard  11746:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11747:   /*                              fractional in yp1 *\/ */
                   11748:   /* aintmean=yp; */
                   11749:   /* yp2=modf((yp1*12),&yp); */
                   11750:   /* mintmean=yp; */
                   11751:   /* yp1=modf((yp2*30.5),&yp); */
                   11752:   /* jintmean=yp; */
                   11753:   /* if(jintmean==0) jintmean=1; */
                   11754:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  11755:   
1.351     brouard  11756:   /* i1=pow(2,cptcoveff); */
                   11757:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  11758:   
1.296     brouard  11759:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   11760:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  11761:   
                   11762:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   11763:   
1.351     brouard  11764:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11765:     k=TKresult[nres];
                   11766:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11767:   /* for(k=1; k<=i1;k++){ */
                   11768:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   11769:   /*     continue; */
                   11770:   /*   if(invalidvarcomb[k]){ */
                   11771:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11772:   /*     continue; */
                   11773:   /*   } */
1.268     brouard  11774:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  11775:     for(j=1;j<=cptcovs;j++){
                   11776:     /* for(j=1;j<=cptcoveff;j++) { */
                   11777:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11778:     /* } */
                   11779:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  11780:     }
1.351     brouard  11781:    /*  fprintf(ficrespij,"******\n"); */
                   11782:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11783:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11784:    /*  } */
1.267     brouard  11785:     fprintf(ficresfb," yearbproj age");
                   11786:     for(j=1; j<=nlstate+ndeath;j++){
                   11787:       for(i=1; i<=nlstate;i++)
1.268     brouard  11788:        fprintf(ficresfb," b%d%d",i,j);
                   11789:       fprintf(ficresfb," b.%d",j);
1.267     brouard  11790:     }
1.296     brouard  11791:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  11792:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   11793:       fprintf(ficresfb,"\n");
1.296     brouard  11794:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  11795:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  11796:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   11797:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  11798:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  11799:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  11800:        nhstepm = nhstepm/hstepm;
                   11801:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11802:        oldm=oldms;savm=savms;
1.268     brouard  11803:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  11804:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  11805:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  11806:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   11807:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   11808:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  11809:        for (h=0; h<=nhstepm; h++){
1.268     brouard  11810:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   11811:            break;
                   11812:          }
                   11813:        }
                   11814:        fprintf(ficresfb,"\n");
1.351     brouard  11815:        /* for(j=1;j<=cptcoveff;j++) */
                   11816:        for(j=1;j<=cptcovs;j++)
                   11817:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11818:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  11819:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  11820:        for(i=1; i<=nlstate+ndeath;i++) {
                   11821:          ppij=0.;ppi=0.;
                   11822:          for(j=1; j<=nlstate;j++) {
                   11823:            /* if (mobilav==1) */
1.269     brouard  11824:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   11825:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   11826:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   11827:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  11828:              /* else { */
                   11829:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   11830:              /* } */
1.268     brouard  11831:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   11832:          } /* end j */
                   11833:          if(ppi <0.99){
                   11834:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11835:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11836:          }
                   11837:          fprintf(ficresfb," %.3f", ppij);
                   11838:        }/* end j */
1.267     brouard  11839:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11840:       } /* end agec */
                   11841:     } /* end yearp */
                   11842:   } /* end k */
1.217     brouard  11843:   
1.267     brouard  11844:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  11845:   
1.267     brouard  11846:   fclose(ficresfb);
                   11847:   printf("End of Computing Back forecasting \n");
                   11848:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  11849:        
1.267     brouard  11850: }
1.217     brouard  11851: 
1.269     brouard  11852: /* Variance of prevalence limit: varprlim */
                   11853:  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  11854:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  11855:  
                   11856:    char fileresvpl[FILENAMELENGTH];  
                   11857:    FILE *ficresvpl;
                   11858:    double **oldm, **savm;
                   11859:    double **varpl; /* Variances of prevalence limits by age */   
                   11860:    int i1, k, nres, j ;
                   11861:    
                   11862:     strcpy(fileresvpl,"VPL_");
                   11863:     strcat(fileresvpl,fileresu);
                   11864:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  11865:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  11866:       exit(0);
                   11867:     }
1.288     brouard  11868:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11869:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  11870:     
                   11871:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11872:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11873:     
                   11874:     i1=pow(2,cptcoveff);
                   11875:     if (cptcovn < 1){i1=1;}
                   11876: 
1.337     brouard  11877:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11878:        k=TKresult[nres];
1.338     brouard  11879:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11880:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  11881:       if(i1 != 1 && TKresult[nres]!= k)
                   11882:        continue;
                   11883:       fprintf(ficresvpl,"\n#****** ");
                   11884:       printf("\n#****** ");
                   11885:       fprintf(ficlog,"\n#****** ");
1.337     brouard  11886:       for(j=1;j<=cptcovs;j++) {
                   11887:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11888:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11889:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11890:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11891:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  11892:       }
1.337     brouard  11893:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11894:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11895:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11896:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11897:       /* }      */
1.269     brouard  11898:       fprintf(ficresvpl,"******\n");
                   11899:       printf("******\n");
                   11900:       fprintf(ficlog,"******\n");
                   11901:       
                   11902:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11903:       oldm=oldms;savm=savms;
                   11904:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   11905:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   11906:       /*}*/
                   11907:     }
                   11908:     
                   11909:     fclose(ficresvpl);
1.288     brouard  11910:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   11911:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  11912: 
                   11913:  }
                   11914: /* Variance of back prevalence: varbprlim */
                   11915:  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){
                   11916:       /*------- Variance of back (stable) prevalence------*/
                   11917: 
                   11918:    char fileresvbl[FILENAMELENGTH];  
                   11919:    FILE  *ficresvbl;
                   11920: 
                   11921:    double **oldm, **savm;
                   11922:    double **varbpl; /* Variances of back prevalence limits by age */   
                   11923:    int i1, k, nres, j ;
                   11924: 
                   11925:    strcpy(fileresvbl,"VBL_");
                   11926:    strcat(fileresvbl,fileresu);
                   11927:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   11928:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   11929:      exit(0);
                   11930:    }
                   11931:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   11932:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   11933:    
                   11934:    
                   11935:    i1=pow(2,cptcoveff);
                   11936:    if (cptcovn < 1){i1=1;}
                   11937:    
1.337     brouard  11938:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11939:      k=TKresult[nres];
1.338     brouard  11940:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11941:     /* for(k=1; k<=i1;k++){ */
                   11942:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   11943:     /*          continue; */
1.269     brouard  11944:        fprintf(ficresvbl,"\n#****** ");
                   11945:        printf("\n#****** ");
                   11946:        fprintf(ficlog,"\n#****** ");
1.337     brouard  11947:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  11948:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11949:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11950:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  11951:        /* for(j=1;j<=cptcoveff;j++) { */
                   11952:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11953:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11954:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11955:        /* } */
                   11956:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11957:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11958:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11959:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  11960:        }
                   11961:        fprintf(ficresvbl,"******\n");
                   11962:        printf("******\n");
                   11963:        fprintf(ficlog,"******\n");
                   11964:        
                   11965:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11966:        oldm=oldms;savm=savms;
                   11967:        
                   11968:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   11969:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   11970:        /*}*/
                   11971:      }
                   11972:    
                   11973:    fclose(ficresvbl);
                   11974:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   11975:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   11976: 
                   11977:  } /* End of varbprlim */
                   11978: 
1.126     brouard  11979: /************** Forecasting *****not tested NB*************/
1.227     brouard  11980: /* 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  11981:   
1.227     brouard  11982: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   11983: /*   int *popage; */
                   11984: /*   double calagedatem, agelim, kk1, kk2; */
                   11985: /*   double *popeffectif,*popcount; */
                   11986: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   11987: /*   /\* double ***mobaverage; *\/ */
                   11988: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  11989: 
1.227     brouard  11990: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11991: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11992: /*   agelim=AGESUP; */
                   11993: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  11994:   
1.227     brouard  11995: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  11996:   
                   11997:   
1.227     brouard  11998: /*   strcpy(filerespop,"POP_");  */
                   11999: /*   strcat(filerespop,fileresu); */
                   12000: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   12001: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   12002: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   12003: /*   } */
                   12004: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   12005: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  12006: 
1.227     brouard  12007: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  12008: 
1.227     brouard  12009: /*   /\* if (mobilav!=0) { *\/ */
                   12010: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   12011: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   12012: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12013: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12014: /*   /\*   } *\/ */
                   12015: /*   /\* } *\/ */
1.126     brouard  12016: 
1.227     brouard  12017: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   12018: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  12019:   
1.227     brouard  12020: /*   agelim=AGESUP; */
1.126     brouard  12021:   
1.227     brouard  12022: /*   hstepm=1; */
                   12023: /*   hstepm=hstepm/stepm;  */
1.218     brouard  12024:        
1.227     brouard  12025: /*   if (popforecast==1) { */
                   12026: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   12027: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   12028: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   12029: /*     }  */
                   12030: /*     popage=ivector(0,AGESUP); */
                   12031: /*     popeffectif=vector(0,AGESUP); */
                   12032: /*     popcount=vector(0,AGESUP); */
1.126     brouard  12033:     
1.227     brouard  12034: /*     i=1;    */
                   12035: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  12036:     
1.227     brouard  12037: /*     imx=i; */
                   12038: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   12039: /*   } */
1.218     brouard  12040:   
1.227     brouard  12041: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   12042: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   12043: /*       k=k+1; */
                   12044: /*       fprintf(ficrespop,"\n#******"); */
                   12045: /*       for(j=1;j<=cptcoveff;j++) { */
                   12046: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   12047: /*       } */
                   12048: /*       fprintf(ficrespop,"******\n"); */
                   12049: /*       fprintf(ficrespop,"# Age"); */
                   12050: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   12051: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  12052:       
1.227     brouard  12053: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   12054: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  12055:        
1.227     brouard  12056: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12057: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12058: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12059:          
1.227     brouard  12060: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12061: /*       oldm=oldms;savm=savms; */
                   12062: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  12063:          
1.227     brouard  12064: /*       for (h=0; h<=nhstepm; h++){ */
                   12065: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12066: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12067: /*         }  */
                   12068: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12069: /*           kk1=0.;kk2=0; */
                   12070: /*           for(i=1; i<=nlstate;i++) {               */
                   12071: /*             if (mobilav==1)  */
                   12072: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   12073: /*             else { */
                   12074: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   12075: /*             } */
                   12076: /*           } */
                   12077: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   12078: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   12079: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   12080: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   12081: /*           } */
                   12082: /*         } */
                   12083: /*         for(i=1; i<=nlstate;i++){ */
                   12084: /*           kk1=0.; */
                   12085: /*           for(j=1; j<=nlstate;j++){ */
                   12086: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   12087: /*           } */
                   12088: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   12089: /*         } */
1.218     brouard  12090:            
1.227     brouard  12091: /*         if (h==(int)(calagedatem+12*cpt)) */
                   12092: /*           for(j=1; j<=nlstate;j++)  */
                   12093: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   12094: /*       } */
                   12095: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12096: /*     } */
                   12097: /*       } */
1.218     brouard  12098:       
1.227     brouard  12099: /*       /\******\/ */
1.218     brouard  12100:       
1.227     brouard  12101: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   12102: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   12103: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12104: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12105: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12106:          
1.227     brouard  12107: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12108: /*       oldm=oldms;savm=savms; */
                   12109: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12110: /*       for (h=0; h<=nhstepm; h++){ */
                   12111: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12112: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12113: /*         }  */
                   12114: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12115: /*           kk1=0.;kk2=0; */
                   12116: /*           for(i=1; i<=nlstate;i++) {               */
                   12117: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   12118: /*           } */
                   12119: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   12120: /*         } */
                   12121: /*       } */
                   12122: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12123: /*     } */
                   12124: /*       } */
                   12125: /*     }  */
                   12126: /*   } */
1.218     brouard  12127:   
1.227     brouard  12128: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  12129:   
1.227     brouard  12130: /*   if (popforecast==1) { */
                   12131: /*     free_ivector(popage,0,AGESUP); */
                   12132: /*     free_vector(popeffectif,0,AGESUP); */
                   12133: /*     free_vector(popcount,0,AGESUP); */
                   12134: /*   } */
                   12135: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12136: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12137: /*   fclose(ficrespop); */
                   12138: /* } /\* End of popforecast *\/ */
1.218     brouard  12139:  
1.126     brouard  12140: int fileappend(FILE *fichier, char *optionfich)
                   12141: {
                   12142:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   12143:     printf("Problem with file: %s\n", optionfich);
                   12144:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   12145:     return (0);
                   12146:   }
                   12147:   fflush(fichier);
                   12148:   return (1);
                   12149: }
                   12150: 
                   12151: 
                   12152: /**************** function prwizard **********************/
                   12153: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   12154: {
                   12155: 
                   12156:   /* Wizard to print covariance matrix template */
                   12157: 
1.164     brouard  12158:   char ca[32], cb[32];
                   12159:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  12160:   int numlinepar;
                   12161: 
                   12162:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12163:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12164:   for(i=1; i <=nlstate; i++){
                   12165:     jj=0;
                   12166:     for(j=1; j <=nlstate+ndeath; j++){
                   12167:       if(j==i) continue;
                   12168:       jj++;
                   12169:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   12170:       printf("%1d%1d",i,j);
                   12171:       fprintf(ficparo,"%1d%1d",i,j);
                   12172:       for(k=1; k<=ncovmodel;k++){
                   12173:        /*        printf(" %lf",param[i][j][k]); */
                   12174:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   12175:        printf(" 0.");
                   12176:        fprintf(ficparo," 0.");
                   12177:       }
                   12178:       printf("\n");
                   12179:       fprintf(ficparo,"\n");
                   12180:     }
                   12181:   }
                   12182:   printf("# Scales (for hessian or gradient estimation)\n");
                   12183:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   12184:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   12185:   for(i=1; i <=nlstate; i++){
                   12186:     jj=0;
                   12187:     for(j=1; j <=nlstate+ndeath; j++){
                   12188:       if(j==i) continue;
                   12189:       jj++;
                   12190:       fprintf(ficparo,"%1d%1d",i,j);
                   12191:       printf("%1d%1d",i,j);
                   12192:       fflush(stdout);
                   12193:       for(k=1; k<=ncovmodel;k++){
                   12194:        /*      printf(" %le",delti3[i][j][k]); */
                   12195:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   12196:        printf(" 0.");
                   12197:        fprintf(ficparo," 0.");
                   12198:       }
                   12199:       numlinepar++;
                   12200:       printf("\n");
                   12201:       fprintf(ficparo,"\n");
                   12202:     }
                   12203:   }
                   12204:   printf("# Covariance matrix\n");
                   12205: /* # 121 Var(a12)\n\ */
                   12206: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12207: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12208: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12209: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12210: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12211: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12212: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12213:   fflush(stdout);
                   12214:   fprintf(ficparo,"# Covariance matrix\n");
                   12215:   /* # 121 Var(a12)\n\ */
                   12216:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12217:   /* #   ...\n\ */
                   12218:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   12219:   
                   12220:   for(itimes=1;itimes<=2;itimes++){
                   12221:     jj=0;
                   12222:     for(i=1; i <=nlstate; i++){
                   12223:       for(j=1; j <=nlstate+ndeath; j++){
                   12224:        if(j==i) continue;
                   12225:        for(k=1; k<=ncovmodel;k++){
                   12226:          jj++;
                   12227:          ca[0]= k+'a'-1;ca[1]='\0';
                   12228:          if(itimes==1){
                   12229:            printf("#%1d%1d%d",i,j,k);
                   12230:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   12231:          }else{
                   12232:            printf("%1d%1d%d",i,j,k);
                   12233:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   12234:            /*  printf(" %.5le",matcov[i][j]); */
                   12235:          }
                   12236:          ll=0;
                   12237:          for(li=1;li <=nlstate; li++){
                   12238:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   12239:              if(lj==li) continue;
                   12240:              for(lk=1;lk<=ncovmodel;lk++){
                   12241:                ll++;
                   12242:                if(ll<=jj){
                   12243:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   12244:                  if(ll<jj){
                   12245:                    if(itimes==1){
                   12246:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12247:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12248:                    }else{
                   12249:                      printf(" 0.");
                   12250:                      fprintf(ficparo," 0.");
                   12251:                    }
                   12252:                  }else{
                   12253:                    if(itimes==1){
                   12254:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   12255:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   12256:                    }else{
                   12257:                      printf(" 0.");
                   12258:                      fprintf(ficparo," 0.");
                   12259:                    }
                   12260:                  }
                   12261:                }
                   12262:              } /* end lk */
                   12263:            } /* end lj */
                   12264:          } /* end li */
                   12265:          printf("\n");
                   12266:          fprintf(ficparo,"\n");
                   12267:          numlinepar++;
                   12268:        } /* end k*/
                   12269:       } /*end j */
                   12270:     } /* end i */
                   12271:   } /* end itimes */
                   12272: 
                   12273: } /* end of prwizard */
                   12274: /******************* Gompertz Likelihood ******************************/
                   12275: double gompertz(double x[])
                   12276: { 
1.302     brouard  12277:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  12278:   int i,n=0; /* n is the size of the sample */
                   12279: 
1.220     brouard  12280:   for (i=1;i<=imx ; i++) {
1.126     brouard  12281:     sump=sump+weight[i];
                   12282:     /*    sump=sump+1;*/
                   12283:     num=num+1;
                   12284:   }
1.302     brouard  12285:   L=0.0;
                   12286:   /* agegomp=AGEGOMP; */
1.126     brouard  12287:   /* for (i=0; i<=imx; i++) 
                   12288:      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]);*/
                   12289: 
1.302     brouard  12290:   for (i=1;i<=imx ; i++) {
                   12291:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   12292:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   12293:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   12294:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   12295:      * +
                   12296:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   12297:      */
                   12298:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   12299:        if (cens[i] == 1){
                   12300:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   12301:        } else if (cens[i] == 0){
1.126     brouard  12302:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.362     brouard  12303:          +log(fabs(x[1])/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   12304:        /* +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM); */  /* To be seen */
1.302     brouard  12305:       } else
                   12306:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  12307:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  12308:        L=L+A*weight[i];
1.126     brouard  12309:        /*      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  12310:      }
                   12311:   }
1.126     brouard  12312: 
1.302     brouard  12313:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  12314:  
                   12315:   return -2*L*num/sump;
                   12316: }
                   12317: 
1.136     brouard  12318: #ifdef GSL
                   12319: /******************* Gompertz_f Likelihood ******************************/
                   12320: double gompertz_f(const gsl_vector *v, void *params)
                   12321: { 
1.302     brouard  12322:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  12323:   double *x= (double *) v->data;
                   12324:   int i,n=0; /* n is the size of the sample */
                   12325: 
                   12326:   for (i=0;i<=imx-1 ; i++) {
                   12327:     sump=sump+weight[i];
                   12328:     /*    sump=sump+1;*/
                   12329:     num=num+1;
                   12330:   }
                   12331:  
                   12332:  
                   12333:   /* for (i=0; i<=imx; i++) 
                   12334:      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]);*/
                   12335:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   12336:   for (i=1;i<=imx ; i++)
                   12337:     {
                   12338:       if (cens[i] == 1 && wav[i]>1)
                   12339:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   12340:       
                   12341:       if (cens[i] == 0 && wav[i]>1)
                   12342:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   12343:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   12344:       
                   12345:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   12346:       if (wav[i] > 1 ) { /* ??? */
                   12347:        LL=LL+A*weight[i];
                   12348:        /*      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]);*/
                   12349:       }
                   12350:     }
                   12351: 
                   12352:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   12353:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   12354:  
                   12355:   return -2*LL*num/sump;
                   12356: }
                   12357: #endif
                   12358: 
1.126     brouard  12359: /******************* Printing html file ***********/
1.201     brouard  12360: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  12361:                  int lastpass, int stepm, int weightopt, char model[],\
                   12362:                  int imx,  double p[],double **matcov,double agemortsup){
                   12363:   int i,k;
                   12364: 
                   12365:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   12366:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   12367:   for (i=1;i<=2;i++) 
                   12368:     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  12369:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  12370:   fprintf(fichtm,"</ul>");
                   12371: 
                   12372: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   12373: 
                   12374:  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>");
                   12375: 
                   12376:  for (k=agegomp;k<(agemortsup-2);k++) 
                   12377:    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]);
                   12378: 
                   12379:  
                   12380:   fflush(fichtm);
                   12381: }
                   12382: 
                   12383: /******************* Gnuplot file **************/
1.201     brouard  12384: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  12385: 
                   12386:   char dirfileres[132],optfileres[132];
1.164     brouard  12387: 
1.359     brouard  12388:   /*int ng;*/
1.126     brouard  12389: 
                   12390: 
                   12391:   /*#ifdef windows */
                   12392:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   12393:     /*#endif */
                   12394: 
                   12395: 
                   12396:   strcpy(dirfileres,optionfilefiname);
                   12397:   strcpy(optfileres,"vpl");
1.199     brouard  12398:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  12399:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  12400:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  12401:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  12402:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   12403: 
                   12404: } 
                   12405: 
1.136     brouard  12406: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   12407: {
1.126     brouard  12408: 
1.136     brouard  12409:   /*-------- data file ----------*/
                   12410:   FILE *fic;
                   12411:   char dummy[]="                         ";
1.359     brouard  12412:   int i = 0, j = 0, n = 0, iv = 0;/* , v;*/
1.223     brouard  12413:   int lstra;
1.136     brouard  12414:   int linei, month, year,iout;
1.302     brouard  12415:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  12416:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  12417:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  12418:   char *stratrunc;
1.223     brouard  12419: 
1.349     brouard  12420:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   12421:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  12422:   
                   12423:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   12424:   
1.136     brouard  12425:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  12426:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12427:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  12428:   }
1.126     brouard  12429: 
1.302     brouard  12430:     /* Is it a BOM UTF-8 Windows file? */
                   12431:   /* First data line */
                   12432:   linei=0;
                   12433:   while(fgets(line, MAXLINE, fic)) {
                   12434:     noffset=0;
                   12435:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12436:     {
                   12437:       noffset=noffset+3;
                   12438:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   12439:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   12440:       fflush(ficlog); return 1;
                   12441:     }
                   12442:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12443:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   12444:     {
                   12445:       noffset=noffset+2;
1.304     brouard  12446:       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);
                   12447:       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  12448:       fflush(ficlog); return 1;
                   12449:     }
                   12450:     else if( line[0] == 0 && line[1] == 0)
                   12451:     {
                   12452:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12453:        noffset=noffset+4;
1.304     brouard  12454:        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);
                   12455:        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  12456:        fflush(ficlog); return 1;
                   12457:       }
                   12458:     } else{
                   12459:       ;/*printf(" Not a BOM file\n");*/
                   12460:     }
                   12461:         /* If line starts with a # it is a comment */
                   12462:     if (line[noffset] == '#') {
                   12463:       linei=linei+1;
                   12464:       break;
                   12465:     }else{
                   12466:       break;
                   12467:     }
                   12468:   }
                   12469:   fclose(fic);
                   12470:   if((fic=fopen(datafile,"r"))==NULL)    {
                   12471:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12472:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   12473:   }
                   12474:   /* Not a Bom file */
                   12475:   
1.136     brouard  12476:   i=1;
                   12477:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   12478:     linei=linei+1;
                   12479:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   12480:       if(line[j] == '\t')
                   12481:        line[j] = ' ';
                   12482:     }
                   12483:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   12484:       ;
                   12485:     };
                   12486:     line[j+1]=0;  /* Trims blanks at end of line */
                   12487:     if(line[0]=='#'){
                   12488:       fprintf(ficlog,"Comment line\n%s\n",line);
                   12489:       printf("Comment line\n%s\n",line);
                   12490:       continue;
                   12491:     }
                   12492:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  12493:     strcpy(line, linetmp);
1.223     brouard  12494:     
                   12495:     /* Loops on waves */
                   12496:     for (j=maxwav;j>=1;j--){
                   12497:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  12498:        cutv(stra, strb, line, ' '); 
                   12499:        if(strb[0]=='.') { /* Missing value */
                   12500:          lval=-1;
                   12501:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  12502:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  12503:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   12504:            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);
                   12505:            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);
                   12506:            return 1;
                   12507:          }
                   12508:        }else{
                   12509:          errno=0;
                   12510:          /* what_kind_of_number(strb); */
                   12511:          dval=strtod(strb,&endptr); 
                   12512:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   12513:          /* if(strb != endptr && *endptr == '\0') */
                   12514:          /*    dval=dlval; */
                   12515:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12516:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12517:            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);
                   12518:            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);
                   12519:            return 1;
                   12520:          }
                   12521:          cotqvar[j][iv][i]=dval; 
1.341     brouard  12522:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  12523:        }
                   12524:        strcpy(line,stra);
1.223     brouard  12525:       }/* end loop ntqv */
1.225     brouard  12526:       
1.223     brouard  12527:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  12528:        cutv(stra, strb, line, ' '); 
                   12529:        if(strb[0]=='.') { /* Missing value */
                   12530:          lval=-1;
                   12531:        }else{
                   12532:          errno=0;
                   12533:          lval=strtol(strb,&endptr,10); 
                   12534:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   12535:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12536:            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);
                   12537:            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);
                   12538:            return 1;
                   12539:          }
                   12540:        }
                   12541:        if(lval <-1 || lval >1){
                   12542:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12543:  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  12544:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12545:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12546:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12547:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12548:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12549:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12550:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  12551:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12552:  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  12553:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12554:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12555:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12556:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12557:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12558:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12559:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  12560:          return 1;
                   12561:        }
1.341     brouard  12562:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  12563:        strcpy(line,stra);
1.223     brouard  12564:       }/* end loop ntv */
1.225     brouard  12565:       
1.223     brouard  12566:       /* Statuses  at wave */
1.137     brouard  12567:       cutv(stra, strb, line, ' '); 
1.223     brouard  12568:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  12569:        lval=-1;
1.136     brouard  12570:       }else{
1.238     brouard  12571:        errno=0;
                   12572:        lval=strtol(strb,&endptr,10); 
                   12573:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  12574:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   12575:          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);
                   12576:          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);
                   12577:          return 1;
                   12578:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  12579:          printf("Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile);fflush(stdout);
                   12580:          fprintf(ficlog,"Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile); fflush(ficlog);
1.238     brouard  12581:          return 1;
                   12582:        }
1.136     brouard  12583:       }
1.225     brouard  12584:       
1.136     brouard  12585:       s[j][i]=lval;
1.225     brouard  12586:       
1.223     brouard  12587:       /* Date of Interview */
1.136     brouard  12588:       strcpy(line,stra);
                   12589:       cutv(stra, strb,line,' ');
1.169     brouard  12590:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12591:       }
1.169     brouard  12592:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  12593:        month=99;
                   12594:        year=9999;
1.136     brouard  12595:       }else{
1.225     brouard  12596:        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);
                   12597:        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);
                   12598:        return 1;
1.136     brouard  12599:       }
                   12600:       anint[j][i]= (double) year; 
1.302     brouard  12601:       mint[j][i]= (double)month;
                   12602:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   12603:       /*       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]); */
                   12604:       /*       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]); */
                   12605:       /* } */
1.136     brouard  12606:       strcpy(line,stra);
1.223     brouard  12607:     } /* End loop on waves */
1.225     brouard  12608:     
1.223     brouard  12609:     /* Date of death */
1.136     brouard  12610:     cutv(stra, strb,line,' '); 
1.169     brouard  12611:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12612:     }
1.169     brouard  12613:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  12614:       month=99;
                   12615:       year=9999;
                   12616:     }else{
1.141     brouard  12617:       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  12618:       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);
                   12619:       return 1;
1.136     brouard  12620:     }
                   12621:     andc[i]=(double) year; 
                   12622:     moisdc[i]=(double) month; 
                   12623:     strcpy(line,stra);
                   12624:     
1.223     brouard  12625:     /* Date of birth */
1.136     brouard  12626:     cutv(stra, strb,line,' '); 
1.169     brouard  12627:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12628:     }
1.169     brouard  12629:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  12630:       month=99;
                   12631:       year=9999;
                   12632:     }else{
1.141     brouard  12633:       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);
                   12634:       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  12635:       return 1;
1.136     brouard  12636:     }
                   12637:     if (year==9999) {
1.141     brouard  12638:       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);
                   12639:       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  12640:       return 1;
                   12641:       
1.136     brouard  12642:     }
                   12643:     annais[i]=(double)(year);
1.302     brouard  12644:     moisnais[i]=(double)(month);
                   12645:     for (j=1;j<=maxwav;j++){
                   12646:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   12647:        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]);
                   12648:        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]);
                   12649:       }
                   12650:     }
                   12651: 
1.136     brouard  12652:     strcpy(line,stra);
1.225     brouard  12653:     
1.223     brouard  12654:     /* Sample weight */
1.136     brouard  12655:     cutv(stra, strb,line,' '); 
                   12656:     errno=0;
                   12657:     dval=strtod(strb,&endptr); 
                   12658:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  12659:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   12660:       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  12661:       fflush(ficlog);
                   12662:       return 1;
                   12663:     }
                   12664:     weight[i]=dval; 
                   12665:     strcpy(line,stra);
1.225     brouard  12666:     
1.223     brouard  12667:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   12668:       cutv(stra, strb, line, ' '); 
                   12669:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  12670:        lval=-1;
1.311     brouard  12671:        coqvar[iv][i]=NAN; 
                   12672:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12673:       }else{
1.225     brouard  12674:        errno=0;
                   12675:        /* what_kind_of_number(strb); */
                   12676:        dval=strtod(strb,&endptr);
                   12677:        /* if(strb != endptr && *endptr == '\0') */
                   12678:        /*   dval=dlval; */
                   12679:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12680:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12681:          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);
                   12682:          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);
                   12683:          return 1;
                   12684:        }
                   12685:        coqvar[iv][i]=dval; 
1.226     brouard  12686:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12687:       }
                   12688:       strcpy(line,stra);
                   12689:     }/* end loop nqv */
1.136     brouard  12690:     
1.223     brouard  12691:     /* Covariate values */
1.136     brouard  12692:     for (j=ncovcol;j>=1;j--){
                   12693:       cutv(stra, strb,line,' '); 
1.223     brouard  12694:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  12695:        lval=-1;
1.136     brouard  12696:       }else{
1.225     brouard  12697:        errno=0;
                   12698:        lval=strtol(strb,&endptr,10); 
                   12699:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12700:          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);
                   12701:          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);
                   12702:          return 1;
                   12703:        }
1.136     brouard  12704:       }
                   12705:       if(lval <-1 || lval >1){
1.225     brouard  12706:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12707:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12708:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12709:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12710:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12711:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12712:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12713:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12714:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  12715:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12716:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12717:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12718:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12719:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12720:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12721:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12722:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12723:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  12724:        return 1;
1.136     brouard  12725:       }
                   12726:       covar[j][i]=(double)(lval);
                   12727:       strcpy(line,stra);
                   12728:     }  
                   12729:     lstra=strlen(stra);
1.225     brouard  12730:     
1.136     brouard  12731:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   12732:       stratrunc = &(stra[lstra-9]);
                   12733:       num[i]=atol(stratrunc);
                   12734:     }
                   12735:     else
                   12736:       num[i]=atol(stra);
                   12737:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   12738:       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;}*/
                   12739:     
                   12740:     i=i+1;
                   12741:   } /* End loop reading  data */
1.225     brouard  12742:   
1.136     brouard  12743:   *imax=i-1; /* Number of individuals */
                   12744:   fclose(fic);
1.225     brouard  12745:   
1.136     brouard  12746:   return (0);
1.164     brouard  12747:   /* endread: */
1.225     brouard  12748:   printf("Exiting readdata: ");
                   12749:   fclose(fic);
                   12750:   return (1);
1.223     brouard  12751: }
1.126     brouard  12752: 
1.234     brouard  12753: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  12754:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  12755:   while (*p2 == ' ')
1.234     brouard  12756:     p2++; 
                   12757:   /* while ((*p1++ = *p2++) !=0) */
                   12758:   /*   ; */
                   12759:   /* do */
                   12760:   /*   while (*p2 == ' ') */
                   12761:   /*     p2++; */
                   12762:   /* while (*p1++ == *p2++); */
                   12763:   *stri=p2; 
1.145     brouard  12764: }
                   12765: 
1.330     brouard  12766: int decoderesult( char resultline[], int nres)
1.230     brouard  12767: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   12768: {
1.235     brouard  12769:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  12770:   char resultsav[MAXLINE];
1.330     brouard  12771:   /* int resultmodel[MAXLINE]; */
1.334     brouard  12772:   /* int modelresult[MAXLINE]; */
1.230     brouard  12773:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   12774: 
1.234     brouard  12775:   removefirstspace(&resultline);
1.332     brouard  12776:   printf("decoderesult:%s\n",resultline);
1.230     brouard  12777: 
1.332     brouard  12778:   strcpy(resultsav,resultline);
1.342     brouard  12779:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  12780:   if (strlen(resultsav) >1){
1.334     brouard  12781:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  12782:   }
1.353     brouard  12783:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  12784:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   12785:     return (0);
                   12786:   }
1.234     brouard  12787:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  12788:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, 1+age+%s.\n",j, cptcovs, model);fflush(ficlog);
                   12789:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, 1+age+%s.\n",j, cptcovs, model);fflush(stdout);
                   12790:     if(j==0)
                   12791:       return 1;
1.234     brouard  12792:   }
1.334     brouard  12793:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  12794:     if(nbocc(resultsav,'=') >1){
1.318     brouard  12795:       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  12796:       /* 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  12797:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  12798:       /* If a blank, then strc="V4=" and strd='\0' */
                   12799:       if(strc[0]=='\0'){
                   12800:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   12801:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   12802:        return 1;
                   12803:       }
1.234     brouard  12804:     }else
                   12805:       cutl(strc,strd,resultsav,'=');
1.318     brouard  12806:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  12807:     
1.230     brouard  12808:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  12809:     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  12810:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   12811:     /* cptcovsel++;     */
                   12812:     if (nbocc(stra,'=') >0)
                   12813:       strcpy(resultsav,stra); /* and analyzes it */
                   12814:   }
1.235     brouard  12815:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12816:   /* 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  12817:   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  12818:     if(Typevar[k1]==0){ /* Single covariate in model */
                   12819:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  12820:       match=0;
1.318     brouard  12821:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12822:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12823:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  12824:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  12825:          break;
                   12826:        }
                   12827:       }
                   12828:       if(match == 0){
1.338     brouard  12829:        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]);
                   12830:        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  12831:        return 1;
1.234     brouard  12832:       }
1.332     brouard  12833:     }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*/
                   12834:       /* We feed resultmodel[k1]=k2; */
                   12835:       match=0;
                   12836:       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 */
                   12837:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12838:          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  12839:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  12840:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  12841:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12842:          break;
                   12843:        }
                   12844:       }
                   12845:       if(match == 0){
1.338     brouard  12846:        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]);
                   12847:        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  12848:       return 1;
                   12849:       }
1.349     brouard  12850:     }else if(Typevar[k1]==2 || Typevar[k1]==3){ /* Product with or without age. We want to get the position in the resultline of the product in the model line*/
1.332     brouard  12851:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   12852:       match=0;
1.342     brouard  12853:       /* 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  12854:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12855:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12856:          /* modelresult[k2]=k1; */
1.342     brouard  12857:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  12858:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12859:        }
                   12860:       }
                   12861:       if(match == 0){
1.349     brouard  12862:        printf("Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   12863:        fprintf(ficlog,"Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  12864:        return 1;
                   12865:       }
                   12866:       match=0;
                   12867:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12868:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12869:          /* modelresult[k2]=k1;*/
1.342     brouard  12870:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  12871:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12872:          break;
                   12873:        }
                   12874:       }
                   12875:       if(match == 0){
1.349     brouard  12876:        printf("Error in result line (Product without age second variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   12877:        fprintf(ficlog,"Error in result line (Product without age second variable or double product with age): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  12878:        return 1;
                   12879:       }
                   12880:     }/* End of testing */
1.333     brouard  12881:   }/* End loop cptcovt */
1.235     brouard  12882:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12883:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  12884:   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)
                   12885:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  12886:     match=0;
1.318     brouard  12887:     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  12888:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  12889:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  12890:          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  12891:          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  12892:          ++match;
                   12893:        }
                   12894:       }
                   12895:     }
                   12896:     if(match == 0){
1.338     brouard  12897:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   12898:       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  12899:       return 1;
1.234     brouard  12900:     }else if(match > 1){
1.338     brouard  12901:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   12902:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  12903:       return 1;
1.234     brouard  12904:     }
                   12905:   }
1.334     brouard  12906:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  12907:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  12908:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  12909:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   12910:   /* 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*/
                   12911:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  12912:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   12913:   /*    1 0 0 0 */
                   12914:   /*    2 1 0 0 */
                   12915:   /*    3 0 1 0 */ 
1.330     brouard  12916:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  12917:   /*    5 0 0 1 */
1.330     brouard  12918:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  12919:   /*    7 0 1 1 */
                   12920:   /*    8 1 1 1 */
1.237     brouard  12921:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   12922:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   12923:   /* V5*age V5 known which value for nres?  */
                   12924:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  12925:   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.
                   12926:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  12927:     /* k counting number of combination of single dummies in the equation model */
                   12928:     /* k4 counting single dummies in the equation model */
                   12929:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  12930:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
1.334     brouard  12931:        /* 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  12932:       /* 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  12933:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  12934:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   12935:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   12936:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   12937:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   12938:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  12939:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  12940:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  12941:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  12942:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   12943:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12944:       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  12945:       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  12946:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  12947:       /* Tinvresult[nres][4]=1 */
1.334     brouard  12948:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   12949:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   12950:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12951:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  12952:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  12953:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  12954:       /* 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  12955:       k4++;;
1.331     brouard  12956:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  12957:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  12958:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  12959:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  12960:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   12961:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   12962:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  12963:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   12964:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12965:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   12966:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   12967:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   12968:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  12969:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  12970:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  12971:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  12972:       /* 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  12973:       k4q++;;
1.350     brouard  12974:     }else if( Dummy[k1]==2 ){ /* For dummy with age product "V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   12975:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  12976:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  12977:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12978:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12979:       /* 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]]); */
                   12980:       }else{
                   12981:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12982:        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)*/
                   12983:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   12984:        precov[nres][k1]=Tvalsel[k3];
                   12985:       }
1.342     brouard  12986:       /* 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  12987:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  12988:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12989:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12990:       /* 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]]); */
                   12991:       }else{
                   12992:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   12993:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   12994:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   12995:        precov[nres][k1]=Tvalsel[k3q];
                   12996:       }
1.342     brouard  12997:       /* printf("Decoderesult Quantitative with age nres=%d, k1=%d, precov[nres=%d][k1=%d]=%f Tvar[%d]=V%d V(k2q=%d)= Tvarsel[%d]=%d, Tvalsel[%d]=%f\n",nres, k1, nres, k1,precov[nres][k1], k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]); */
1.349     brouard  12998:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  12999:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  13000:       /* 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  13001:     }else{
1.332     brouard  13002:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   13003:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  13004:     }
                   13005:   }
1.234     brouard  13006:   
1.334     brouard  13007:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  13008:   return (0);
                   13009: }
1.235     brouard  13010: 
1.230     brouard  13011: int decodemodel( char model[], int lastobs)
                   13012:  /**< This routine decodes the model and returns:
1.224     brouard  13013:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   13014:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   13015:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   13016:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   13017:        * - cptcovage number of covariates with age*products =2
                   13018:        * - cptcovs number of simple covariates
1.339     brouard  13019:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  13020:        * - 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  13021:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  13022:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  13023:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   13024:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   13025:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   13026:        */
1.319     brouard  13027: /* 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  13028: {
1.359     brouard  13029:   int i, j, k, ks;/* , v;*/
1.349     brouard  13030:   int n,m;
                   13031:   int  j1, k1, k11, k12, k2, k3, k4;
                   13032:   char modelsav[300];
                   13033:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  13034:   char *strpt;
1.349     brouard  13035:   int  **existcomb;
                   13036:   
                   13037:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   13038:   for(i=1;i<=NCOVMAX;i++)
                   13039:     for(j=1;j<=NCOVMAX;j++)
                   13040:       existcomb[i][j]=0;
                   13041:     
1.145     brouard  13042:   /*removespace(model);*/
1.136     brouard  13043:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  13044:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  13045:     if (strstr(model,"AGE") !=0){
1.192     brouard  13046:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   13047:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  13048:       return 1;
                   13049:     }
1.141     brouard  13050:     if (strstr(model,"v") !=0){
1.338     brouard  13051:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   13052:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  13053:       return 1;
                   13054:     }
1.187     brouard  13055:     strcpy(modelsav,model); 
                   13056:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  13057:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  13058:       if(strpt != model){
1.338     brouard  13059:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13060:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13061:  corresponding column of parameters.\n",model);
1.338     brouard  13062:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13063:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13064:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  13065:        return 1;
1.225     brouard  13066:       }
1.187     brouard  13067:       nagesqr=1;
                   13068:       if (strstr(model,"+age*age") !=0)
1.234     brouard  13069:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  13070:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  13071:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  13072:       else 
1.234     brouard  13073:        substrchaine(modelsav, model, "age*age");
1.187     brouard  13074:     }else
                   13075:       nagesqr=0;
1.349     brouard  13076:     if (strlen(modelsav) >1){ /* V2 +V3 +V4 +V6 +V7 +V6*V2 +V7*V2 +V6*V3 +V7*V3 +V6*V4 +V7*V4 +age*V2 +age*V3 +age*V4 +age*V6 +age*V7 +age*V6*V2 +V7*V2 +age*V6*V3 +age*V7*V3 +age*V6*V4 +age*V7*V4 */
1.187     brouard  13077:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   13078:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  13079:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  13080:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  13081:                     * cst, age and age*age 
                   13082:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   13083:       /* including age products which are counted in cptcovage.
                   13084:        * but the covariates which are products must be treated 
                   13085:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  13086:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   13087:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  13088:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  13089:       cptcovprodage=0;
                   13090:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  13091:       
1.187     brouard  13092:       /*   Design
                   13093:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   13094:        *  <          ncovcol=8                >
                   13095:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   13096:        *   k=  1    2      3       4     5       6      7        8
                   13097:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  13098:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  13099:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   13100:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  13101:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   13102:        *  Tage[++cptcovage]=k
1.345     brouard  13103:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  13104:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   13105:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   13106:        *  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
                   13107:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   13108:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   13109:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  13110:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  13111:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   13112:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  13113:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   13114:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  13115:        * p Tprod[1]@2={                         6, 5}
                   13116:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   13117:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   13118:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  13119:        *How to reorganize? Tvars(orted)
1.187     brouard  13120:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   13121:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   13122:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   13123:        * Struct []
                   13124:        */
1.225     brouard  13125:       
1.187     brouard  13126:       /* This loop fills the array Tvar from the string 'model'.*/
                   13127:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   13128:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   13129:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   13130:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   13131:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   13132:       /*       k=1 Tvar[1]=2 (from V2) */
                   13133:       /*       k=5 Tvar[5] */
                   13134:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  13135:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  13136:       /*       } */
1.198     brouard  13137:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  13138:       /*
                   13139:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  13140:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   13141:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   13142:       }
1.187     brouard  13143:       cptcovage=0;
1.351     brouard  13144: 
                   13145:       /* First loop in order to calculate */
                   13146:       /* for age*VN*Vm
                   13147:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   13148:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   13149:       */
                   13150:       /* Needs  FixedV[Tvardk[k][1]] */
                   13151:       /* For others:
                   13152:        * Sets  Typevar[k];
                   13153:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13154:        *       Tposprod[k]=k11;
                   13155:        *       Tprod[k11]=k;
                   13156:        *       Tvardk[k][1] =m;
                   13157:        * Needs FixedV[Tvardk[k][1]] == 0
                   13158:       */
                   13159:       
1.319     brouard  13160:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   13161:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   13162:                                         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" */
                   13163:        if (nbocc(modelsav,'+')==0)
                   13164:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  13165:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   13166:        /*scanf("%d",i);*/
1.349     brouard  13167:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age OR double product with age strb=age*V6*V2 or V6*V2*age or V6*age*V2 */
                   13168:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 OR strb=age*V6*V2 strc=V6*V2 strd=age OR c=V2*age OR c=age*V2  */
                   13169:          if(strchr(strc,'*')) { /**< Model with age and DOUBLE product: allowed since 0.99r44, strc=V6*V2 or V2*age or age*V2, strd=age or V6 or V6   */
                   13170:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   13171:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   13172:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   13173:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   13174:              /* We want strb=Vn*Vm */
                   13175:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   13176:                 strcpy(strb,strd);
                   13177:                 strcat(strb,"*");
                   13178:                 strcat(strb,stre);
                   13179:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   13180:                 strcpy(strb,strf);
                   13181:                 strcat(strb,"*");
                   13182:                 strcat(strb,stre);
                   13183:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   13184:               }
1.351     brouard  13185:              /* printf("DEBUG FIXED k=%d, Tage[k]=%d, Tvar[Tage[k]=%d,FixedV[Tvar[Tage[k]]]=%d\n",k,Tage[k],Tvar[Tage[k]],FixedV[Tvar[Tage[k]]]); */
                   13186:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  13187:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   13188:              strcpy(stre,strb); /* save full b in stre */
                   13189:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   13190:              strcpy(strf,strc); /* save short c in new short f */
                   13191:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   13192:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   13193:             }
                   13194:             cptcovdageprod++; /* double product with age  Which product is it? */
                   13195:             /* strcpy(strb,strc);  /\* strb was age*V6*V2 or V6*V2*age or V6*age*V2 IS now V6*V2 or V2*age or age*V2 *\/ */
                   13196:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  13197:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  13198:            n=atoi(stre);
1.234     brouard  13199:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  13200:            m=atoi(strc);
                   13201:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   13202:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   13203:            if(existcomb[n][m] == 0){
                   13204:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   13205:              printf("Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
                   13206:              fprintf(ficlog,"Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
                   13207:              fflush(ficlog);
                   13208:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   13209:              k12++;
                   13210:              existcomb[n][m]=k1;
                   13211:              existcomb[m][n]=k1;
                   13212:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   13213:              Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2+ age*V6*V3 Gives the k position of the k1 double product Vn*Vm or age*Vn*Vm*/
                   13214:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   13215:              Tvard[k1][1] =m; /* m 1 for V1*/
                   13216:              Tvardk[k][1] =m; /* m 1 for V1*/
                   13217:              Tvard[k1][2] =n; /* n 4 for V4*/
                   13218:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  13219: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  13220:              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 */
                   13221:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   13222:                  /* Computes the new covariate which is a product of
                   13223:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13224:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13225:                }
                   13226:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13227:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13228:                k12++;
                   13229:                FixedV[ncovcolt+k12]=0;
                   13230:              }else{ /*End of FixedV */
                   13231:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   13232:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13233:                k12++;
                   13234:                FixedV[ncovcolt+k12]=1;
                   13235:              }
                   13236:            }else{  /* k1 Vn*Vm already exists */
                   13237:              k11=existcomb[n][m];
                   13238:              Tposprod[k]=k11; /* OK */
                   13239:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   13240:              Tvardk[k][1]=m;
                   13241:              Tvardk[k][2]=n;
                   13242:              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 */
                   13243:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13244:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13245:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13246:                Tvar[Tage[cptcovage]]=k1;
                   13247:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13248:                k12++;
                   13249:                FixedV[ncovcolt+k12]=0;
                   13250:              }else{ /* Already exists but time varying (and age) */
                   13251:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13252:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13253:                /* Tvar[Tage[cptcovage]]=k1; */
                   13254:                cptcovprodvage++;
                   13255:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13256:                k12++;
                   13257:                FixedV[ncovcolt+k12]=1;
                   13258:              }
                   13259:            }
                   13260:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   13261:            /* Tvar[k]=k11; /\* HERY *\/ */
                   13262:          } else {/* simple product strb=age*Vn so that c=Vn and d=age, or strb=Vn*age so that c=age and d=Vn, or b=Vn*Vm so that c=Vm and d=Vn */
                   13263:             cptcovprod++;
                   13264:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   13265:               /* covar is not filled and then is empty */
                   13266:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   13267:               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 */
                   13268:               Typevar[k]=1;  /* 1 for age product */
                   13269:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   13270:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   13271:              if( FixedV[Tvar[k]] == 0){
                   13272:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13273:              }else{
                   13274:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   13275:              }
                   13276:               /*printf("stre=%s ", stre);*/
                   13277:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   13278:               cutl(stre,strb,strc,'V');
                   13279:               Tvar[k]=atoi(stre);
                   13280:               Typevar[k]=1;  /* 1 for age product */
                   13281:               cptcovage++;
                   13282:               Tage[cptcovage]=k;
                   13283:              if( FixedV[Tvar[k]] == 0){
                   13284:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13285:              }else{
                   13286:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  13287:              }
1.349     brouard  13288:             }else{ /*  for product Vn*Vm */
                   13289:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   13290:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   13291:              n=atoi(stre);
                   13292:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   13293:              m=atoi(strc);
                   13294:              k1++;
                   13295:              cptcovprodnoage++;
                   13296:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   13297:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13298:                fprintf(ficlog,"Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13299:                fflush(ficlog);
                   13300:                k11=existcomb[n][m];
                   13301:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13302:                Tposprod[k]=k11;
                   13303:                Tprod[k11]=k;
                   13304:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13305:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   13306:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   13307:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   13308:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   13309:                existcomb[n][m]=k1;
                   13310:                existcomb[m][n]=k1;
                   13311:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   13312:                                                    because this model-covariate is a construction we invent a new column
                   13313:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   13314:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   13315:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   13316:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   13317:                /* Please remark that the new variables are model dependent */
                   13318:                /* If we have 4 variable but the model uses only 3, like in
                   13319:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   13320:                 *  k=     1     2      3   4     5        6        7       8
                   13321:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   13322:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   13323:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   13324:                 */
                   13325:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   13326:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   13327:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   13328:                Tvard[k1][1] =m; /* m 1 for V1*/
                   13329:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13330:                Tvard[k1][2] =n; /* n 4 for V4*/
                   13331:                Tvardk[k][2] =n; /* n 4 for V4*/
                   13332:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   13333:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   13334:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   13335:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   13336:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   13337:                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 */
                   13338:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   13339:                    /* Computes the new covariate which is a product of
                   13340:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13341:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13342:                  }
                   13343:                  /* TvarVV[k2]=n; */
                   13344:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13345:                  /* TvarVV[k2+1]=m; */
                   13346:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13347:                }else{ /* not FixedV */
                   13348:                  /* TvarVV[k2]=n; */
                   13349:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13350:                  /* TvarVV[k2+1]=m; */
                   13351:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13352:                }                 
                   13353:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   13354:            } /*  End of product Vn*Vm */
                   13355:           } /* End of age*double product or simple product */
                   13356:        }else { /* not a product */
1.234     brouard  13357:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   13358:          /*  scanf("%d",i);*/
                   13359:          cutl(strd,strc,strb,'V');
                   13360:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   13361:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   13362:          Tvar[k]=atoi(strd);
                   13363:          Typevar[k]=0;  /* 0 for simple covariates */
                   13364:        }
                   13365:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  13366:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  13367:                                  scanf("%d",i);*/
1.187     brouard  13368:       } /* end of loop + on total covariates */
1.351     brouard  13369: 
                   13370:       
1.187     brouard  13371:     } /* end if strlen(modelsave == 0) age*age might exist */
                   13372:   } /* end if strlen(model == 0) */
1.349     brouard  13373:   cptcovs=cptcovt - cptcovdageprod - cptcovprod;/**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age + age*v4*V3=> V1 + V3 =4+1-3=2  */
                   13374: 
1.136     brouard  13375:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   13376:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  13377:   
1.136     brouard  13378:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  13379:      printf("cptcovprod=%d ", cptcovprod);
                   13380:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   13381:      scanf("%d ",i);*/
                   13382: 
                   13383: 
1.230     brouard  13384: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   13385:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  13386: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   13387:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   13388:    k =           1    2   3     4       5       6      7      8        9
                   13389:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  13390:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  13391:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   13392:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   13393:          Tmodelind[combination of covar]=k;
1.225     brouard  13394: */  
                   13395: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  13396:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  13397:   /* 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  13398:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  13399:   printf("Model=1+age+%s\n\
1.349     brouard  13400: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
1.227     brouard  13401: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13402: 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  13403:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  13404: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
1.227     brouard  13405: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13406: 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  13407:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   13408:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  13409: 
                   13410: 
                   13411:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   13412: 
                   13413:   
1.349     brouard  13414:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0,ncovva=0,ncovvta=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt loop on k from model */
1.234     brouard  13415:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  13416:       Fixed[k]= 0;
                   13417:       Dummy[k]= 0;
1.225     brouard  13418:       ncoveff++;
1.232     brouard  13419:       ncovf++;
1.234     brouard  13420:       nsd++;
                   13421:       modell[k].maintype= FTYPE;
                   13422:       TvarsD[nsd]=Tvar[k];
                   13423:       TvarsDind[nsd]=k;
1.330     brouard  13424:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  13425:       TvarF[ncovf]=Tvar[k];
                   13426:       TvarFind[ncovf]=k;
                   13427:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13428:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  13429:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
1.240     brouard  13430:     }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  13431:       Fixed[k]= 0;
                   13432:       Dummy[k]= 1;
1.230     brouard  13433:       nqfveff++;
1.234     brouard  13434:       modell[k].maintype= FTYPE;
                   13435:       modell[k].subtype= FQ;
                   13436:       nsq++;
1.334     brouard  13437:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   13438:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  13439:       ncovf++;
1.234     brouard  13440:       TvarF[ncovf]=Tvar[k];
                   13441:       TvarFind[ncovf]=k;
1.231     brouard  13442:       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  13443:       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  13444:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  13445:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13446:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13447:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13448:       ncovvt++;
                   13449:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13450:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   13451: 
1.227     brouard  13452:       Fixed[k]= 1;
                   13453:       Dummy[k]= 0;
1.225     brouard  13454:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  13455:       modell[k].maintype= VTYPE;
                   13456:       modell[k].subtype= VD;
                   13457:       nsd++;
                   13458:       TvarsD[nsd]=Tvar[k];
                   13459:       TvarsDind[nsd]=k;
1.330     brouard  13460:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  13461:       ncovv++; /* Only simple time varying variables */
                   13462:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13463:       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  13464:       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 */
                   13465:       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  13466:       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);
                   13467:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  13468:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  13469:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13470:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13471:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13472:       ncovvt++;
                   13473:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13474:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13475:       
1.234     brouard  13476:       Fixed[k]= 1;
                   13477:       Dummy[k]= 1;
                   13478:       nqtveff++;
                   13479:       modell[k].maintype= VTYPE;
                   13480:       modell[k].subtype= VQ;
                   13481:       ncovv++; /* Only simple time varying variables */
                   13482:       nsq++;
1.334     brouard  13483:       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) */
                   13484:       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  13485:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13486:       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  13487:       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 */
                   13488:       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  13489:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   13490:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  13491:       /* printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%Ad,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv); */
1.342     brouard  13492:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  13493:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  13494:       ncova++;
                   13495:       TvarA[ncova]=Tvar[k];
                   13496:       TvarAind[ncova]=k;
1.349     brouard  13497:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13498:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
1.231     brouard  13499:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  13500:        Fixed[k]= 2;
                   13501:        Dummy[k]= 2;
                   13502:        modell[k].maintype= ATYPE;
                   13503:        modell[k].subtype= APFD;
1.349     brouard  13504:        ncovta++;
                   13505:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   13506:        TvarAVVAind[ncovta]=k;
1.240     brouard  13507:        /* ncoveff++; */
1.227     brouard  13508:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  13509:        Fixed[k]= 2;
                   13510:        Dummy[k]= 3;
                   13511:        modell[k].maintype= ATYPE;
                   13512:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  13513:        ncovta++;
                   13514:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13515:        TvarAVVAind[ncovta]=k;
1.240     brouard  13516:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  13517:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  13518:        Fixed[k]= 3;
                   13519:        Dummy[k]= 2;
                   13520:        modell[k].maintype= ATYPE;
                   13521:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  13522:        ncovva++;
                   13523:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13524:        TvarVVAind[ncovva]=k;
                   13525:        ncovta++;
                   13526:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13527:        TvarAVVAind[ncovta]=k;
1.240     brouard  13528:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  13529:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  13530:        Fixed[k]= 3;
                   13531:        Dummy[k]= 3;
                   13532:        modell[k].maintype= ATYPE;
                   13533:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  13534:        ncovva++;
                   13535:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   13536:        TvarVVAind[ncovva]=k;
                   13537:        ncovta++;
                   13538:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13539:        TvarAVVAind[ncovta]=k;
1.240     brouard  13540:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  13541:       }
1.349     brouard  13542:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   13543:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   13544:       if(FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* Needs a fixed product Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol V3*V2 */
                   13545:       printf("MEMORY ERRORR k=%d Tvardk[k][1]=%d, Tvardk[k][2]=%d, FixedV[Tvardk[k][1]]=%d,FixedV[Tvardk[k][2]]=%d\n ",k,Tvardk[k][1],Tvardk[k][2],FixedV[Tvardk[k][1]],FixedV[Tvardk[k][2]]);
                   13546:        Fixed[k]= 0;
                   13547:        Dummy[k]= 0;
                   13548:        ncoveff++;
                   13549:        ncovf++;
                   13550:        /* ncovv++; */
                   13551:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   13552:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13553:        /* ncovv++; */
                   13554:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   13555:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13556:        modell[k].maintype= FTYPE;
                   13557:        TvarF[ncovf]=Tvar[k];
                   13558:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   13559:        TvarFind[ncovf]=k;
                   13560:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13561:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13562:       }else{/* product varying Vn * Vm without age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
                   13563:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13564:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13565:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13566:        k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
                   13567:        ncovvt++;
                   13568:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13569:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13570:        ncovvt++;
                   13571:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13572:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13573:        
                   13574:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13575:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13576:        
                   13577:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13578:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   13579:            Fixed[k]= 1;
                   13580:            Dummy[k]= 0;
                   13581:            modell[k].maintype= FTYPE;
                   13582:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   13583:            ncovf++; /* Fixed variables without age */
                   13584:            TvarF[ncovf]=Tvar[k];
                   13585:            TvarFind[ncovf]=k;
                   13586:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   13587:            Fixed[k]= 0;  /* Fixed product */
                   13588:            Dummy[k]= 1;
                   13589:            modell[k].maintype= FTYPE;
                   13590:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   13591:            ncovf++; /* Varying variables without age */
                   13592:            TvarF[ncovf]=Tvar[k];
                   13593:            TvarFind[ncovf]=k;
                   13594:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   13595:            Fixed[k]= 1;
                   13596:            Dummy[k]= 0;
                   13597:            modell[k].maintype= VTYPE;
                   13598:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   13599:            ncovv++; /* Varying variables without age */
                   13600:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13601:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   13602:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   13603:            Fixed[k]= 1;
                   13604:            Dummy[k]= 1;
                   13605:            modell[k].maintype= VTYPE;
                   13606:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   13607:            ncovv++; /* Varying variables without age */
                   13608:            TvarV[ncovv]=Tvar[k];
                   13609:            TvarVind[ncovv]=k;
                   13610:          }
                   13611:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13612:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   13613:            Fixed[k]= 0;  /*  Fixed product */
                   13614:            Dummy[k]= 1;
                   13615:            modell[k].maintype= FTYPE;
                   13616:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   13617:            ncovf++; /* Fixed variables without age */
                   13618:            TvarF[ncovf]=Tvar[k];
                   13619:            TvarFind[ncovf]=k;
                   13620:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   13621:            Fixed[k]= 1;
                   13622:            Dummy[k]= 1;
                   13623:            modell[k].maintype= VTYPE;
                   13624:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   13625:            ncovv++; /* Varying variables without age */
                   13626:            TvarV[ncovv]=Tvar[k];
                   13627:            TvarVind[ncovv]=k;
                   13628:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   13629:            Fixed[k]= 1;
                   13630:            Dummy[k]= 1;
                   13631:            modell[k].maintype= VTYPE;
                   13632:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   13633:            ncovv++; /* Varying variables without age */
                   13634:            TvarV[ncovv]=Tvar[k];
                   13635:            TvarVind[ncovv]=k;
                   13636:            ncovv++; /* Varying variables without age */
                   13637:            TvarV[ncovv]=Tvar[k];
                   13638:            TvarVind[ncovv]=k;
                   13639:          }
                   13640:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   13641:          if(Tvard[k1][2] <=ncovcol){
                   13642:            Fixed[k]= 1;
                   13643:            Dummy[k]= 1;
                   13644:            modell[k].maintype= VTYPE;
                   13645:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   13646:            ncovv++; /* Varying variables without age */
                   13647:            TvarV[ncovv]=Tvar[k];
                   13648:            TvarVind[ncovv]=k;
                   13649:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13650:            Fixed[k]= 1;
                   13651:            Dummy[k]= 1;
                   13652:            modell[k].maintype= VTYPE;
                   13653:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   13654:            ncovv++; /* Varying variables without age */
                   13655:            TvarV[ncovv]=Tvar[k];
                   13656:            TvarVind[ncovv]=k;
                   13657:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13658:            Fixed[k]= 1;
                   13659:            Dummy[k]= 0;
                   13660:            modell[k].maintype= VTYPE;
                   13661:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   13662:            ncovv++; /* Varying variables without age */
                   13663:            TvarV[ncovv]=Tvar[k];
                   13664:            TvarVind[ncovv]=k;
                   13665:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13666:            Fixed[k]= 1;
                   13667:            Dummy[k]= 1;
                   13668:            modell[k].maintype= VTYPE;
                   13669:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   13670:            ncovv++; /* Varying variables without age */
                   13671:            TvarV[ncovv]=Tvar[k];
                   13672:            TvarVind[ncovv]=k;
                   13673:          }
                   13674:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   13675:          if(Tvard[k1][2] <=ncovcol){
                   13676:            Fixed[k]= 1;
                   13677:            Dummy[k]= 1;
                   13678:            modell[k].maintype= VTYPE;
                   13679:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   13680:            ncovv++; /* Varying variables without age */
                   13681:            TvarV[ncovv]=Tvar[k];
                   13682:            TvarVind[ncovv]=k;
                   13683:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13684:            Fixed[k]= 1;
                   13685:            Dummy[k]= 1;
                   13686:            modell[k].maintype= VTYPE;
                   13687:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   13688:            ncovv++; /* Varying variables without age */
                   13689:            TvarV[ncovv]=Tvar[k];
                   13690:            TvarVind[ncovv]=k;
                   13691:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13692:            Fixed[k]= 1;
                   13693:            Dummy[k]= 1;
                   13694:            modell[k].maintype= VTYPE;
                   13695:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   13696:            ncovv++; /* Varying variables without age */
                   13697:            TvarV[ncovv]=Tvar[k];
                   13698:            TvarVind[ncovv]=k;
                   13699:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13700:            Fixed[k]= 1;
                   13701:            Dummy[k]= 1;
                   13702:            modell[k].maintype= VTYPE;
                   13703:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   13704:            ncovv++; /* Varying variables without age */
                   13705:            TvarV[ncovv]=Tvar[k];
                   13706:            TvarVind[ncovv]=k;
                   13707:          }
                   13708:        }else{
                   13709:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13710:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13711:        } /*end k1*/
                   13712:       }
                   13713:     }else if(Typevar[k] == 3){  /* product Vn * Vm with age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
1.339     brouard  13714:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  13715:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13716:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13717:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
                   13718:       ncova++;
                   13719:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13720:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13721:       ncova++;
                   13722:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13723:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  13724: 
1.349     brouard  13725:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13726:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13727:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   13728:        ncovta++;
                   13729:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13730:        TvarAVVAind[ncovta]=k;
                   13731:        ncovta++;
                   13732:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13733:        TvarAVVAind[ncovta]=k;
                   13734:       }else{
                   13735:        ncovva++;  /* HERY  reached */
                   13736:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   13737:        TvarVVAind[ncovva]=k;
                   13738:        ncovva++;
                   13739:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   13740:        TvarVVAind[ncovva]=k;
                   13741:        ncovta++;
                   13742:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13743:        TvarAVVAind[ncovta]=k;
                   13744:        ncovta++;
                   13745:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13746:        TvarAVVAind[ncovta]=k;
                   13747:       }
1.339     brouard  13748:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13749:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  13750:          Fixed[k]= 2;
                   13751:          Dummy[k]= 2;
1.240     brouard  13752:          modell[k].maintype= FTYPE;
                   13753:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  13754:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   13755:          /* TvarFind[ncova]=k; */
1.339     brouard  13756:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  13757:          Fixed[k]= 2;  /* Fixed product */
                   13758:          Dummy[k]= 3;
1.240     brouard  13759:          modell[k].maintype= FTYPE;
                   13760:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  13761:          /* TvarF[ncova]=Tvar[k]; */
                   13762:          /* TvarFind[ncova]=k; */
1.339     brouard  13763:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  13764:          Fixed[k]= 3;
                   13765:          Dummy[k]= 2;
1.240     brouard  13766:          modell[k].maintype= VTYPE;
                   13767:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  13768:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13769:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  13770:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  13771:          Fixed[k]= 3;
                   13772:          Dummy[k]= 3;
1.240     brouard  13773:          modell[k].maintype= VTYPE;
                   13774:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  13775:          /* ncovv++; /\* Varying variables without age *\/ */
                   13776:          /* TvarV[ncovv]=Tvar[k]; */
                   13777:          /* TvarVind[ncovv]=k; */
1.240     brouard  13778:        }
1.339     brouard  13779:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13780:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  13781:          Fixed[k]= 2;  /*  Fixed product */
                   13782:          Dummy[k]= 2;
1.240     brouard  13783:          modell[k].maintype= FTYPE;
                   13784:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  13785:          /* ncova++; /\* Fixed variables with age *\/ */
                   13786:          /* TvarF[ncovf]=Tvar[k]; */
                   13787:          /* TvarFind[ncovf]=k; */
1.339     brouard  13788:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  13789:          Fixed[k]= 2;
                   13790:          Dummy[k]= 3;
1.240     brouard  13791:          modell[k].maintype= VTYPE;
                   13792:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  13793:          /* ncova++; /\* Varying variables with age *\/ */
                   13794:          /* TvarV[ncova]=Tvar[k]; */
                   13795:          /* TvarVind[ncova]=k; */
1.339     brouard  13796:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  13797:          Fixed[k]= 3;
                   13798:          Dummy[k]= 2;
1.240     brouard  13799:          modell[k].maintype= VTYPE;
                   13800:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  13801:          ncova++; /* Varying variables without age */
                   13802:          TvarV[ncova]=Tvar[k];
                   13803:          TvarVind[ncova]=k;
                   13804:          /* ncova++; /\* Varying variables without age *\/ */
                   13805:          /* TvarV[ncova]=Tvar[k]; */
                   13806:          /* TvarVind[ncova]=k; */
1.240     brouard  13807:        }
1.339     brouard  13808:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  13809:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13810:          Fixed[k]= 2;
                   13811:          Dummy[k]= 2;
1.240     brouard  13812:          modell[k].maintype= VTYPE;
                   13813:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  13814:          /* ncova++; /\* Varying variables with age *\/ */
                   13815:          /* TvarV[ncova]=Tvar[k]; */
                   13816:          /* TvarVind[ncova]=k; */
1.240     brouard  13817:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13818:          Fixed[k]= 2;
                   13819:          Dummy[k]= 3;
1.240     brouard  13820:          modell[k].maintype= VTYPE;
                   13821:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  13822:          /* ncova++; /\* Varying variables with age *\/ */
                   13823:          /* TvarV[ncova]=Tvar[k]; */
                   13824:          /* TvarVind[ncova]=k; */
1.240     brouard  13825:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13826:          Fixed[k]= 3;
                   13827:          Dummy[k]= 2;
1.240     brouard  13828:          modell[k].maintype= VTYPE;
                   13829:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  13830:          /* ncova++; /\* Varying variables with age *\/ */
                   13831:          /* TvarV[ncova]=Tvar[k]; */
                   13832:          /* TvarVind[ncova]=k; */
1.240     brouard  13833:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13834:          Fixed[k]= 3;
                   13835:          Dummy[k]= 3;
1.240     brouard  13836:          modell[k].maintype= VTYPE;
                   13837:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  13838:          /* ncova++; /\* Varying variables with age *\/ */
                   13839:          /* TvarV[ncova]=Tvar[k]; */
                   13840:          /* TvarVind[ncova]=k; */
1.240     brouard  13841:        }
1.339     brouard  13842:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  13843:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13844:          Fixed[k]= 2;
                   13845:          Dummy[k]= 2;
1.240     brouard  13846:          modell[k].maintype= VTYPE;
                   13847:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  13848:          /* ncova++; /\* Varying variables with age *\/ */
                   13849:          /* TvarV[ncova]=Tvar[k]; */
                   13850:          /* TvarVind[ncova]=k; */
1.240     brouard  13851:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13852:          Fixed[k]= 2;
                   13853:          Dummy[k]= 3;
1.240     brouard  13854:          modell[k].maintype= VTYPE;
                   13855:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  13856:          /* ncova++; /\* Varying variables with age *\/ */
                   13857:          /* TvarV[ncova]=Tvar[k]; */
                   13858:          /* TvarVind[ncova]=k; */
1.240     brouard  13859:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13860:          Fixed[k]= 3;
                   13861:          Dummy[k]= 2;
1.240     brouard  13862:          modell[k].maintype= VTYPE;
                   13863:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  13864:          /* ncova++; /\* Varying variables with age *\/ */
                   13865:          /* TvarV[ncova]=Tvar[k]; */
                   13866:          /* TvarVind[ncova]=k; */
1.240     brouard  13867:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13868:          Fixed[k]= 3;
                   13869:          Dummy[k]= 3;
1.240     brouard  13870:          modell[k].maintype= VTYPE;
                   13871:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  13872:          /* ncova++; /\* Varying variables with age *\/ */
                   13873:          /* TvarV[ncova]=Tvar[k]; */
                   13874:          /* TvarVind[ncova]=k; */
1.240     brouard  13875:        }
1.227     brouard  13876:       }else{
1.240     brouard  13877:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13878:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13879:       } /*end k1*/
1.349     brouard  13880:     } else{
1.226     brouard  13881:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   13882:       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  13883:     }
1.342     brouard  13884:     /* 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]); */
                   13885:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  13886:     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]);
                   13887:   }
1.349     brouard  13888:   ncovvta=ncovva;
1.227     brouard  13889:   /* Searching for doublons in the model */
                   13890:   for(k1=1; k1<= cptcovt;k1++){
                   13891:     for(k2=1; k2 <k1;k2++){
1.285     brouard  13892:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   13893:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  13894:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   13895:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  13896:            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]);
                   13897:            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  13898:            return(1);
                   13899:          }
                   13900:        }else if (Typevar[k1] ==2){
                   13901:          k3=Tposprod[k1];
                   13902:          k4=Tposprod[k2];
                   13903:          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  13904:            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]]);
                   13905:            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  13906:            return(1);
                   13907:          }
                   13908:        }
1.227     brouard  13909:       }
                   13910:     }
1.225     brouard  13911:   }
                   13912:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   13913:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  13914:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   13915:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  13916: 
                   13917:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  13918:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  13919:   /*endread:*/
1.225     brouard  13920:   printf("Exiting decodemodel: ");
                   13921:   return (1);
1.136     brouard  13922: }
                   13923: 
1.169     brouard  13924: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  13925: {/* Check ages at death */
1.136     brouard  13926:   int i, m;
1.218     brouard  13927:   int firstone=0;
                   13928:   
1.136     brouard  13929:   for (i=1; i<=imx; i++) {
                   13930:     for(m=2; (m<= maxwav); m++) {
                   13931:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   13932:        anint[m][i]=9999;
1.216     brouard  13933:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   13934:          s[m][i]=-1;
1.136     brouard  13935:       }
                   13936:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  13937:        *nberr = *nberr + 1;
1.218     brouard  13938:        if(firstone == 0){
                   13939:          firstone=1;
1.260     brouard  13940:        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  13941:        }
1.262     brouard  13942:        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  13943:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  13944:       }
                   13945:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  13946:        (*nberr)++;
1.259     brouard  13947:        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  13948:        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  13949:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  13950:       }
                   13951:     }
                   13952:   }
                   13953: 
                   13954:   for (i=1; i<=imx; i++)  {
                   13955:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   13956:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  13957:       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  13958:        if (s[m][i] >= nlstate+1) {
1.169     brouard  13959:          if(agedc[i]>0){
                   13960:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  13961:              agev[m][i]=agedc[i];
1.214     brouard  13962:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  13963:            }else {
1.136     brouard  13964:              if ((int)andc[i]!=9999){
                   13965:                nbwarn++;
                   13966:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   13967:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   13968:                agev[m][i]=-1;
                   13969:              }
                   13970:            }
1.169     brouard  13971:          } /* agedc > 0 */
1.214     brouard  13972:        } /* end if */
1.136     brouard  13973:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   13974:                                 years but with the precision of a month */
                   13975:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   13976:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   13977:            agev[m][i]=1;
                   13978:          else if(agev[m][i] < *agemin){ 
                   13979:            *agemin=agev[m][i];
                   13980:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   13981:          }
                   13982:          else if(agev[m][i] >*agemax){
                   13983:            *agemax=agev[m][i];
1.156     brouard  13984:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  13985:          }
                   13986:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   13987:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  13988:        } /* en if 9*/
1.136     brouard  13989:        else { /* =9 */
1.214     brouard  13990:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  13991:          agev[m][i]=1;
                   13992:          s[m][i]=-1;
                   13993:        }
                   13994:       }
1.214     brouard  13995:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  13996:        agev[m][i]=1;
1.214     brouard  13997:       else{
                   13998:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   13999:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   14000:        agev[m][i]=0;
                   14001:       }
                   14002:     } /* End for lastpass */
                   14003:   }
1.136     brouard  14004:     
                   14005:   for (i=1; i<=imx; i++)  {
                   14006:     for(m=firstpass; (m<=lastpass); m++){
                   14007:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  14008:        (*nberr)++;
1.136     brouard  14009:        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);     
                   14010:        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);     
                   14011:        return 1;
                   14012:       }
                   14013:     }
                   14014:   }
                   14015: 
                   14016:   /*for (i=1; i<=imx; i++){
                   14017:   for (m=firstpass; (m<lastpass); m++){
                   14018:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   14019: }
                   14020: 
                   14021: }*/
                   14022: 
                   14023: 
1.139     brouard  14024:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   14025:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  14026: 
                   14027:   return (0);
1.164     brouard  14028:  /* endread:*/
1.136     brouard  14029:     printf("Exiting calandcheckages: ");
                   14030:     return (1);
                   14031: }
                   14032: 
1.172     brouard  14033: #if defined(_MSC_VER)
                   14034: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14035: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14036: //#include "stdafx.h"
                   14037: //#include <stdio.h>
                   14038: //#include <tchar.h>
                   14039: //#include <windows.h>
                   14040: //#include <iostream>
                   14041: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   14042: 
                   14043: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14044: 
                   14045: BOOL IsWow64()
                   14046: {
                   14047:        BOOL bIsWow64 = FALSE;
                   14048: 
                   14049:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   14050:        //  (HANDLE, PBOOL);
                   14051: 
                   14052:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14053: 
                   14054:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   14055:        const char funcName[] = "IsWow64Process";
                   14056:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   14057:                GetProcAddress(module, funcName);
                   14058: 
                   14059:        if (NULL != fnIsWow64Process)
                   14060:        {
                   14061:                if (!fnIsWow64Process(GetCurrentProcess(),
                   14062:                        &bIsWow64))
                   14063:                        //throw std::exception("Unknown error");
                   14064:                        printf("Unknown error\n");
                   14065:        }
                   14066:        return bIsWow64 != FALSE;
                   14067: }
                   14068: #endif
1.177     brouard  14069: 
1.191     brouard  14070: void syscompilerinfo(int logged)
1.292     brouard  14071: {
                   14072: #include <stdint.h>
                   14073: 
                   14074:   /* #include "syscompilerinfo.h"*/
1.185     brouard  14075:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   14076:    /* /GS /W3 /Gy
                   14077:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   14078:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   14079:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  14080:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   14081:    */ 
                   14082:    /* 64 bits */
1.185     brouard  14083:    /*
                   14084:      /GS /W3 /Gy
                   14085:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   14086:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   14087:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   14088:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   14089:    /* Optimization are useless and O3 is slower than O2 */
                   14090:    /*
                   14091:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   14092:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   14093:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   14094:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   14095:    */
1.186     brouard  14096:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  14097:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   14098:       /PDB:"visual studio
                   14099:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   14100:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   14101:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   14102:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   14103:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   14104:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   14105:       uiAccess='false'"
                   14106:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   14107:       /NOLOGO /TLBID:1
                   14108:    */
1.292     brouard  14109: 
                   14110: 
1.177     brouard  14111: #if defined __INTEL_COMPILER
1.178     brouard  14112: #if defined(__GNUC__)
                   14113:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   14114: #endif
1.177     brouard  14115: #elif defined(__GNUC__) 
1.179     brouard  14116: #ifndef  __APPLE__
1.174     brouard  14117: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  14118: #endif
1.177     brouard  14119:    struct utsname sysInfo;
1.178     brouard  14120:    int cross = CROSS;
                   14121:    if (cross){
                   14122:           printf("Cross-");
1.191     brouard  14123:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  14124:    }
1.174     brouard  14125: #endif
                   14126: 
1.191     brouard  14127:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  14128: #if defined(__clang__)
1.191     brouard  14129:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  14130: #endif
                   14131: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  14132:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  14133: #endif
                   14134: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  14135:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  14136: #endif
                   14137: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  14138:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  14139: #endif
                   14140: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  14141:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  14142: #endif
                   14143: #if defined(_MSC_VER)
1.191     brouard  14144:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  14145: #endif
                   14146: #if defined(__PGI)
1.191     brouard  14147:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  14148: #endif
                   14149: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  14150:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  14151: #endif
1.191     brouard  14152:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  14153:    
1.167     brouard  14154: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   14155: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   14156:     // Windows (x64 and x86)
1.191     brouard  14157:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  14158: #elif __unix__ // all unices, not all compilers
                   14159:     // Unix
1.191     brouard  14160:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  14161: #elif __linux__
                   14162:     // linux
1.191     brouard  14163:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  14164: #elif __APPLE__
1.174     brouard  14165:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  14166:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  14167: #endif
                   14168: 
                   14169: /*  __MINGW32__          */
                   14170: /*  __CYGWIN__  */
                   14171: /* __MINGW64__  */
                   14172: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   14173: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   14174: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   14175: /* _WIN64  // Defined for applications for Win64. */
                   14176: /* _M_X64 // Defined for compilations that target x64 processors. */
                   14177: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  14178: 
1.167     brouard  14179: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  14180:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  14181: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  14182:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  14183: #else
1.191     brouard  14184:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  14185: #endif
                   14186: 
1.169     brouard  14187: #if defined(__GNUC__)
                   14188: # if defined(__GNUC_PATCHLEVEL__)
                   14189: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14190:                             + __GNUC_MINOR__ * 100 \
                   14191:                             + __GNUC_PATCHLEVEL__)
                   14192: # else
                   14193: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14194:                             + __GNUC_MINOR__ * 100)
                   14195: # endif
1.174     brouard  14196:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  14197:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  14198: 
                   14199:    if (uname(&sysInfo) != -1) {
                   14200:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  14201:         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  14202:    }
                   14203:    else
                   14204:       perror("uname() error");
1.179     brouard  14205:    //#ifndef __INTEL_COMPILER 
                   14206: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  14207:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  14208:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  14209: #endif
1.169     brouard  14210: #endif
1.172     brouard  14211: 
1.286     brouard  14212:    //   void main ()
1.172     brouard  14213:    //   {
1.169     brouard  14214: #if defined(_MSC_VER)
1.174     brouard  14215:    if (IsWow64()){
1.191     brouard  14216:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   14217:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  14218:    }
                   14219:    else{
1.191     brouard  14220:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   14221:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  14222:    }
1.172     brouard  14223:    //     printf("\nPress Enter to continue...");
                   14224:    //     getchar();
                   14225:    //   }
                   14226: 
1.169     brouard  14227: #endif
                   14228:    
1.167     brouard  14229: 
1.219     brouard  14230: }
1.136     brouard  14231: 
1.219     brouard  14232: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  14233:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  14234:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  14235:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  14236:   /* double ftolpl = 1.e-10; */
1.180     brouard  14237:   double age, agebase, agelim;
1.203     brouard  14238:   double tot;
1.180     brouard  14239: 
1.202     brouard  14240:   strcpy(filerespl,"PL_");
                   14241:   strcat(filerespl,fileresu);
                   14242:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  14243:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   14244:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  14245:   }
1.288     brouard  14246:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   14247:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  14248:   pstamp(ficrespl);
1.288     brouard  14249:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  14250:   fprintf(ficrespl,"#Age ");
                   14251:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   14252:   fprintf(ficrespl,"\n");
1.180     brouard  14253:   
1.219     brouard  14254:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  14255: 
1.219     brouard  14256:   agebase=ageminpar;
                   14257:   agelim=agemaxpar;
1.180     brouard  14258: 
1.227     brouard  14259:   /* i1=pow(2,ncoveff); */
1.234     brouard  14260:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  14261:   if (cptcovn < 1){i1=1;}
1.180     brouard  14262: 
1.337     brouard  14263:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  14264:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14265:       k=TKresult[nres];
1.338     brouard  14266:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14267:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   14268:       /*       continue; */
1.235     brouard  14269: 
1.238     brouard  14270:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14271:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   14272:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   14273:       /* k=k+1; */
                   14274:       /* to clean */
1.332     brouard  14275:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  14276:       fprintf(ficrespl,"#******");
                   14277:       printf("#******");
                   14278:       fprintf(ficlog,"#******");
1.337     brouard  14279:       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  14280:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  14281:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14282:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14283:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14284:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14285:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14286:       }
                   14287:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14288:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14289:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14290:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14291:       /* } */
1.238     brouard  14292:       fprintf(ficrespl,"******\n");
                   14293:       printf("******\n");
                   14294:       fprintf(ficlog,"******\n");
                   14295:       if(invalidvarcomb[k]){
                   14296:        printf("\nCombination (%d) ignored because no case \n",k); 
                   14297:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   14298:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   14299:        continue;
                   14300:       }
1.219     brouard  14301: 
1.238     brouard  14302:       fprintf(ficrespl,"#Age ");
1.337     brouard  14303:       /* for(j=1;j<=cptcoveff;j++) { */
                   14304:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14305:       /* } */
                   14306:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   14307:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14308:       }
                   14309:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   14310:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  14311:     
1.238     brouard  14312:       for (age=agebase; age<=agelim; age++){
                   14313:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  14314:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   14315:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  14316:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  14317:        /* for(j=1;j<=cptcoveff;j++) */
                   14318:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14319:        for(j=1;j<=cptcovs;j++)
                   14320:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14321:        tot=0.;
                   14322:        for(i=1; i<=nlstate;i++){
                   14323:          tot +=  prlim[i][i];
                   14324:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   14325:        }
                   14326:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   14327:       } /* Age */
                   14328:       /* was end of cptcod */
1.337     brouard  14329:     } /* nres */
                   14330:   /* } /\* for each combination *\/ */
1.219     brouard  14331:   return 0;
1.180     brouard  14332: }
                   14333: 
1.218     brouard  14334: 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  14335:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  14336:        
                   14337:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   14338:    * at any age between ageminpar and agemaxpar
                   14339:         */
1.235     brouard  14340:   int i, j, k, i1, nres=0 ;
1.217     brouard  14341:   /* double ftolpl = 1.e-10; */
                   14342:   double age, agebase, agelim;
                   14343:   double tot;
1.218     brouard  14344:   /* double ***mobaverage; */
                   14345:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  14346: 
                   14347:   strcpy(fileresplb,"PLB_");
                   14348:   strcat(fileresplb,fileresu);
                   14349:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  14350:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   14351:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  14352:   }
1.288     brouard  14353:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   14354:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  14355:   pstamp(ficresplb);
1.288     brouard  14356:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  14357:   fprintf(ficresplb,"#Age ");
                   14358:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   14359:   fprintf(ficresplb,"\n");
                   14360:   
1.218     brouard  14361:   
                   14362:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   14363:   
                   14364:   agebase=ageminpar;
                   14365:   agelim=agemaxpar;
                   14366:   
                   14367:   
1.227     brouard  14368:   i1=pow(2,cptcoveff);
1.218     brouard  14369:   if (cptcovn < 1){i1=1;}
1.227     brouard  14370:   
1.238     brouard  14371:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  14372:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14373:       k=TKresult[nres];
                   14374:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   14375:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   14376:      /*        continue; */
                   14377:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  14378:       fprintf(ficresplb,"#******");
                   14379:       printf("#******");
                   14380:       fprintf(ficlog,"#******");
1.338     brouard  14381:       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) */
                   14382:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14383:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14384:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14385:       }
1.338     brouard  14386:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   14387:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14388:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14389:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14390:       /* } */
                   14391:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14392:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14393:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14394:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14395:       /* } */
1.238     brouard  14396:       fprintf(ficresplb,"******\n");
                   14397:       printf("******\n");
                   14398:       fprintf(ficlog,"******\n");
                   14399:       if(invalidvarcomb[k]){
                   14400:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   14401:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   14402:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   14403:        continue;
                   14404:       }
1.218     brouard  14405:     
1.238     brouard  14406:       fprintf(ficresplb,"#Age ");
1.338     brouard  14407:       for(j=1;j<=cptcovs;j++) {
                   14408:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14409:       }
                   14410:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   14411:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  14412:     
                   14413:     
1.238     brouard  14414:       for (age=agebase; age<=agelim; age++){
                   14415:        /* for (age=agebase; age<=agebase; age++){ */
                   14416:        if(mobilavproj > 0){
                   14417:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   14418:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14419:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  14420:        }else if (mobilavproj == 0){
                   14421:          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);
                   14422:          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);
                   14423:          exit(1);
                   14424:        }else{
                   14425:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14426:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  14427:          /* printf("TOTOT\n"); */
                   14428:           /* exit(1); */
1.238     brouard  14429:        }
                   14430:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  14431:        for(j=1;j<=cptcovs;j++)
                   14432:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14433:        tot=0.;
                   14434:        for(i=1; i<=nlstate;i++){
                   14435:          tot +=  bprlim[i][i];
                   14436:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   14437:        }
                   14438:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   14439:       } /* Age */
                   14440:       /* was end of cptcod */
1.255     brouard  14441:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  14442:     /* } /\* end of any combination *\/ */
1.238     brouard  14443:   } /* end of nres */  
1.218     brouard  14444:   /* hBijx(p, bage, fage); */
                   14445:   /* fclose(ficrespijb); */
                   14446:   
                   14447:   return 0;
1.217     brouard  14448: }
1.218     brouard  14449:  
1.180     brouard  14450: int hPijx(double *p, int bage, int fage){
                   14451:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  14452:   /* to be optimized with precov */
1.180     brouard  14453:   int stepsize;
                   14454:   int agelim;
                   14455:   int hstepm;
                   14456:   int nhstepm;
1.359     brouard  14457:   int h, i, i1, j, k, nres=0;
1.180     brouard  14458: 
                   14459:   double agedeb;
                   14460:   double ***p3mat;
                   14461: 
1.337     brouard  14462:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   14463:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   14464:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14465:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14466:   }
                   14467:   printf("Computing pij: result on file '%s' \n", filerespij);
                   14468:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   14469:   
                   14470:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14471:   /*if (stepm<=24) stepsize=2;*/
                   14472:   
                   14473:   agelim=AGESUP;
                   14474:   hstepm=stepsize*YEARM; /* Every year of age */
                   14475:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   14476:   
                   14477:   /* hstepm=1;   aff par mois*/
                   14478:   pstamp(ficrespij);
                   14479:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   14480:   i1= pow(2,cptcoveff);
                   14481:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14482:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14483:   /*   k=k+1;  */
                   14484:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14485:     k=TKresult[nres];
1.338     brouard  14486:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14487:     /* for(k=1; k<=i1;k++){ */
                   14488:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   14489:     /*         continue; */
                   14490:     fprintf(ficrespij,"\n#****** ");
                   14491:     for(j=1;j<=cptcovs;j++){
                   14492:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14493:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14494:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14495:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14496:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14497:     }
                   14498:     fprintf(ficrespij,"******\n");
                   14499:     
                   14500:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   14501:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   14502:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   14503:       
                   14504:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14505:       
                   14506:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14507:       oldm=oldms;savm=savms;
                   14508:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   14509:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   14510:       for(i=1; i<=nlstate;i++)
                   14511:        for(j=1; j<=nlstate+ndeath;j++)
                   14512:          fprintf(ficrespij," %1d-%1d",i,j);
                   14513:       fprintf(ficrespij,"\n");
                   14514:       for (h=0; h<=nhstepm; h++){
                   14515:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14516:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  14517:        for(i=1; i<=nlstate;i++)
                   14518:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14519:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  14520:        fprintf(ficrespij,"\n");
                   14521:       }
1.337     brouard  14522:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14523:       fprintf(ficrespij,"\n");
1.180     brouard  14524:     }
1.337     brouard  14525:   }
                   14526:   /*}*/
                   14527:   return 0;
1.180     brouard  14528: }
1.218     brouard  14529:  
                   14530:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  14531:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  14532:     /* To be optimized with precov */
1.217     brouard  14533:   int stepsize;
1.218     brouard  14534:   /* int agelim; */
                   14535:        int ageminl;
1.217     brouard  14536:   int hstepm;
                   14537:   int nhstepm;
1.238     brouard  14538:   int h, i, i1, j, k, nres;
1.218     brouard  14539:        
1.217     brouard  14540:   double agedeb;
                   14541:   double ***p3mat;
1.218     brouard  14542:        
                   14543:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   14544:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   14545:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14546:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14547:   }
                   14548:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   14549:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   14550:   
                   14551:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14552:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  14553:   
1.218     brouard  14554:   /* agelim=AGESUP; */
1.289     brouard  14555:   ageminl=AGEINF; /* was 30 */
1.218     brouard  14556:   hstepm=stepsize*YEARM; /* Every year of age */
                   14557:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   14558:   
                   14559:   /* hstepm=1;   aff par mois*/
                   14560:   pstamp(ficrespijb);
1.255     brouard  14561:   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  14562:   i1= pow(2,cptcoveff);
1.218     brouard  14563:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14564:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14565:   /*   k=k+1;  */
1.238     brouard  14566:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14567:     k=TKresult[nres];
1.338     brouard  14568:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14569:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14570:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   14571:     /*         continue; */
                   14572:     fprintf(ficrespijb,"\n#****** ");
                   14573:     for(j=1;j<=cptcovs;j++){
1.338     brouard  14574:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  14575:       /* for(j=1;j<=cptcoveff;j++) */
                   14576:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14577:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14578:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14579:     }
                   14580:     fprintf(ficrespijb,"******\n");
                   14581:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   14582:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   14583:       continue;
                   14584:     }
                   14585:     
                   14586:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   14587:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   14588:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   14589:       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 */
                   14590:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   14591:       
                   14592:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14593:       
                   14594:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   14595:       /* and memory limitations if stepm is small */
                   14596:       
                   14597:       /* oldm=oldms;savm=savms; */
                   14598:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   14599:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   14600:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   14601:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   14602:       for(i=1; i<=nlstate;i++)
                   14603:        for(j=1; j<=nlstate+ndeath;j++)
                   14604:          fprintf(ficrespijb," %1d-%1d",i,j);
                   14605:       fprintf(ficrespijb,"\n");
                   14606:       for (h=0; h<=nhstepm; h++){
                   14607:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14608:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   14609:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  14610:        for(i=1; i<=nlstate;i++)
                   14611:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14612:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  14613:        fprintf(ficrespijb,"\n");
1.337     brouard  14614:       }
                   14615:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14616:       fprintf(ficrespijb,"\n");
                   14617:     } /* end age deb */
                   14618:     /* } /\* end combination *\/ */
1.238     brouard  14619:   } /* end nres */
1.218     brouard  14620:   return 0;
                   14621:  } /*  hBijx */
1.217     brouard  14622: 
1.180     brouard  14623: 
1.136     brouard  14624: /***********************************************/
                   14625: /**************** Main Program *****************/
                   14626: /***********************************************/
                   14627: 
                   14628: int main(int argc, char *argv[])
                   14629: {
                   14630: #ifdef GSL
                   14631:   const gsl_multimin_fminimizer_type *T;
                   14632:   size_t iteri = 0, it;
                   14633:   int rval = GSL_CONTINUE;
                   14634:   int status = GSL_SUCCESS;
                   14635:   double ssval;
                   14636: #endif
                   14637:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  14638:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   14639:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  14640:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  14641:   int jj, ll, li, lj, lk;
1.136     brouard  14642:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  14643:   int num_filled;
1.136     brouard  14644:   int itimes;
                   14645:   int NDIM=2;
                   14646:   int vpopbased=0;
1.235     brouard  14647:   int nres=0;
1.258     brouard  14648:   int endishere=0;
1.277     brouard  14649:   int noffset=0;
1.274     brouard  14650:   int ncurrv=0; /* Temporary variable */
                   14651:   
1.164     brouard  14652:   char ca[32], cb[32];
1.136     brouard  14653:   /*  FILE *fichtm; *//* Html File */
                   14654:   /* FILE *ficgp;*/ /*Gnuplot File */
                   14655:   struct stat info;
1.191     brouard  14656:   double agedeb=0.;
1.194     brouard  14657: 
                   14658:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  14659:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  14660: 
1.361     brouard  14661:   double stdpercent; /* for computing the std error of percent e.i: e.i/e.. */
1.165     brouard  14662:   double fret;
1.191     brouard  14663:   double dum=0.; /* Dummy variable */
1.359     brouard  14664:   /* double*** p3mat;*/
1.218     brouard  14665:   /* double ***mobaverage; */
1.319     brouard  14666:   double wald;
1.164     brouard  14667: 
1.351     brouard  14668:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  14669:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   14670: 
1.234     brouard  14671:   char  modeltemp[MAXLINE];
1.332     brouard  14672:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  14673:   
1.136     brouard  14674:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  14675:   char *tok, *val; /* pathtot */
1.334     brouard  14676:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.359     brouard  14677:   int c, h; /* c2; */
1.191     brouard  14678:   int jl=0;
                   14679:   int i1, j1, jk, stepsize=0;
1.194     brouard  14680:   int count=0;
                   14681: 
1.164     brouard  14682:   int *tab; 
1.136     brouard  14683:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  14684:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   14685:   /* double anprojf, mprojf, jprojf; */
                   14686:   /* double jintmean,mintmean,aintmean;   */
                   14687:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14688:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14689:   double yrfproj= 10.0; /* Number of years of forward projections */
                   14690:   double yrbproj= 10.0; /* Number of years of backward projections */
                   14691:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  14692:   int mobilav=0,popforecast=0;
1.191     brouard  14693:   int hstepm=0, nhstepm=0;
1.136     brouard  14694:   int agemortsup;
                   14695:   float  sumlpop=0.;
                   14696:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   14697:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   14698: 
1.191     brouard  14699:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  14700:   double ftolpl=FTOL;
                   14701:   double **prlim;
1.217     brouard  14702:   double **bprlim;
1.317     brouard  14703:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   14704:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  14705:   double ***paramstart; /* Matrix of starting parameter values */
                   14706:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  14707:   double **matcov; /* Matrix of covariance */
1.203     brouard  14708:   double **hess; /* Hessian matrix */
1.136     brouard  14709:   double ***delti3; /* Scale */
                   14710:   double *delti; /* Scale */
                   14711:   double ***eij, ***vareij;
1.359     brouard  14712:   //double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  14713: 
1.136     brouard  14714:   double *epj, vepp;
1.164     brouard  14715: 
1.273     brouard  14716:   double dateprev1, dateprev2;
1.296     brouard  14717:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   14718:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   14719: 
1.217     brouard  14720: 
1.136     brouard  14721:   double **ximort;
1.145     brouard  14722:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  14723:   int *dcwave;
                   14724: 
1.164     brouard  14725:   char z[1]="c";
1.136     brouard  14726: 
                   14727:   /*char  *strt;*/
                   14728:   char strtend[80];
1.126     brouard  14729: 
1.164     brouard  14730: 
1.126     brouard  14731: /*   setlocale (LC_ALL, ""); */
                   14732: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   14733: /*   textdomain (PACKAGE); */
                   14734: /*   setlocale (LC_CTYPE, ""); */
                   14735: /*   setlocale (LC_MESSAGES, ""); */
                   14736: 
                   14737:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  14738:   rstart_time = time(NULL);  
                   14739:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   14740:   start_time = *localtime(&rstart_time);
1.126     brouard  14741:   curr_time=start_time;
1.157     brouard  14742:   /*tml = *localtime(&start_time.tm_sec);*/
                   14743:   /* strcpy(strstart,asctime(&tml)); */
                   14744:   strcpy(strstart,asctime(&start_time));
1.126     brouard  14745: 
                   14746: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  14747: /*  tp.tm_sec = tp.tm_sec +86400; */
                   14748: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  14749: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   14750: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   14751: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  14752: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  14753: /*   strt=asctime(&tmg); */
                   14754: /*   printf("Time(after) =%s",strstart);  */
                   14755: /*  (void) time (&time_value);
                   14756: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   14757: *  tm = *localtime(&time_value);
                   14758: *  strstart=asctime(&tm);
                   14759: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   14760: */
                   14761: 
                   14762:   nberr=0; /* Number of errors and warnings */
                   14763:   nbwarn=0;
1.184     brouard  14764: #ifdef WIN32
                   14765:   _getcwd(pathcd, size);
                   14766: #else
1.126     brouard  14767:   getcwd(pathcd, size);
1.184     brouard  14768: #endif
1.191     brouard  14769:   syscompilerinfo(0);
1.359     brouard  14770:   printf("\nIMaCh prax version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  14771:   if(argc <=1){
                   14772:     printf("\nEnter the parameter file name: ");
1.205     brouard  14773:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   14774:       printf("ERROR Empty parameter file name\n");
                   14775:       goto end;
                   14776:     }
1.126     brouard  14777:     i=strlen(pathr);
                   14778:     if(pathr[i-1]=='\n')
                   14779:       pathr[i-1]='\0';
1.156     brouard  14780:     i=strlen(pathr);
1.205     brouard  14781:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  14782:       pathr[i-1]='\0';
1.205     brouard  14783:     }
                   14784:     i=strlen(pathr);
                   14785:     if( i==0 ){
                   14786:       printf("ERROR Empty parameter file name\n");
                   14787:       goto end;
                   14788:     }
                   14789:     for (tok = pathr; tok != NULL; ){
1.126     brouard  14790:       printf("Pathr |%s|\n",pathr);
                   14791:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   14792:       printf("val= |%s| pathr=%s\n",val,pathr);
                   14793:       strcpy (pathtot, val);
                   14794:       if(pathr[0] == '\0') break; /* Dirty */
                   14795:     }
                   14796:   }
1.281     brouard  14797:   else if (argc<=2){
                   14798:     strcpy(pathtot,argv[1]);
                   14799:   }
1.126     brouard  14800:   else{
                   14801:     strcpy(pathtot,argv[1]);
1.281     brouard  14802:     strcpy(z,argv[2]);
                   14803:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  14804:   }
                   14805:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   14806:   /*cygwin_split_path(pathtot,path,optionfile);
                   14807:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   14808:   /* cutv(path,optionfile,pathtot,'\\');*/
                   14809: 
                   14810:   /* Split argv[0], imach program to get pathimach */
                   14811:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   14812:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14813:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14814:  /*   strcpy(pathimach,argv[0]); */
                   14815:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   14816:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   14817:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  14818: #ifdef WIN32
                   14819:   _chdir(path); /* Can be a relative path */
                   14820:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   14821: #else
1.126     brouard  14822:   chdir(path); /* Can be a relative path */
1.184     brouard  14823:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   14824: #endif
                   14825:   printf("Current directory %s!\n",pathcd);
1.126     brouard  14826:   strcpy(command,"mkdir ");
                   14827:   strcat(command,optionfilefiname);
                   14828:   if((outcmd=system(command)) != 0){
1.169     brouard  14829:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  14830:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   14831:     /* fclose(ficlog); */
                   14832: /*     exit(1); */
                   14833:   }
                   14834: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   14835: /*     perror("mkdir"); */
                   14836: /*   } */
                   14837: 
                   14838:   /*-------- arguments in the command line --------*/
                   14839: 
1.186     brouard  14840:   /* Main Log file */
1.126     brouard  14841:   strcat(filelog, optionfilefiname);
                   14842:   strcat(filelog,".log");    /* */
                   14843:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   14844:     printf("Problem with logfile %s\n",filelog);
                   14845:     goto end;
                   14846:   }
                   14847:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  14848:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  14849:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   14850:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   14851:  path=%s \n\
                   14852:  optionfile=%s\n\
                   14853:  optionfilext=%s\n\
1.156     brouard  14854:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  14855: 
1.197     brouard  14856:   syscompilerinfo(1);
1.167     brouard  14857: 
1.126     brouard  14858:   printf("Local time (at start):%s",strstart);
                   14859:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   14860:   fflush(ficlog);
                   14861: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  14862: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  14863: 
                   14864:   /* */
                   14865:   strcpy(fileres,"r");
                   14866:   strcat(fileres, optionfilefiname);
1.201     brouard  14867:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  14868:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  14869:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  14870: 
1.186     brouard  14871:   /* Main ---------arguments file --------*/
1.126     brouard  14872: 
                   14873:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  14874:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   14875:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  14876:     fflush(ficlog);
1.149     brouard  14877:     /* goto end; */
                   14878:     exit(70); 
1.126     brouard  14879:   }
                   14880: 
                   14881:   strcpy(filereso,"o");
1.201     brouard  14882:   strcat(filereso,fileresu);
1.126     brouard  14883:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   14884:     printf("Problem with Output resultfile: %s\n", filereso);
                   14885:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   14886:     fflush(ficlog);
                   14887:     goto end;
                   14888:   }
1.278     brouard  14889:       /*-------- Rewriting parameter file ----------*/
                   14890:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   14891:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   14892:   strcat(rfileres,".");    /* */
                   14893:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   14894:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   14895:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   14896:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   14897:     fflush(ficlog);
                   14898:     goto end;
                   14899:   }
                   14900:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  14901: 
1.278     brouard  14902:                                      
1.126     brouard  14903:   /* Reads comments: lines beginning with '#' */
                   14904:   numlinepar=0;
1.277     brouard  14905:   /* Is it a BOM UTF-8 Windows file? */
                   14906:   /* First parameter line */
1.197     brouard  14907:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  14908:     noffset=0;
                   14909:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   14910:     {
                   14911:       noffset=noffset+3;
                   14912:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   14913:     }
1.302     brouard  14914: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   14915:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  14916:     {
                   14917:       noffset=noffset+2;
                   14918:       printf("# File is an UTF16BE BOM file\n");
                   14919:     }
                   14920:     else if( line[0] == 0 && line[1] == 0)
                   14921:     {
                   14922:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   14923:        noffset=noffset+4;
                   14924:        printf("# File is an UTF16BE BOM file\n");
                   14925:       }
                   14926:     } else{
                   14927:       ;/*printf(" Not a BOM file\n");*/
                   14928:     }
                   14929:   
1.197     brouard  14930:     /* If line starts with a # it is a comment */
1.277     brouard  14931:     if (line[noffset] == '#') {
1.197     brouard  14932:       numlinepar++;
                   14933:       fputs(line,stdout);
                   14934:       fputs(line,ficparo);
1.278     brouard  14935:       fputs(line,ficres);
1.197     brouard  14936:       fputs(line,ficlog);
                   14937:       continue;
                   14938:     }else
                   14939:       break;
                   14940:   }
                   14941:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   14942:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   14943:     if (num_filled != 5) {
                   14944:       printf("Should be 5 parameters\n");
1.283     brouard  14945:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  14946:     }
1.126     brouard  14947:     numlinepar++;
1.197     brouard  14948:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  14949:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14950:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14951:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  14952:   }
                   14953:   /* Second parameter line */
                   14954:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  14955:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   14956:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  14957:     if (line[0] == '#') {
                   14958:       numlinepar++;
1.283     brouard  14959:       printf("%s",line);
                   14960:       fprintf(ficres,"%s",line);
                   14961:       fprintf(ficparo,"%s",line);
                   14962:       fprintf(ficlog,"%s",line);
1.197     brouard  14963:       continue;
                   14964:     }else
                   14965:       break;
                   14966:   }
1.223     brouard  14967:   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", \
                   14968:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   14969:     if (num_filled != 11) {
                   14970:       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  14971:       printf("but line=%s\n",line);
1.283     brouard  14972:       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");
                   14973:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  14974:     }
1.286     brouard  14975:     if( lastpass > maxwav){
                   14976:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14977:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14978:       fflush(ficlog);
                   14979:       goto end;
                   14980:     }
                   14981:       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  14982:     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  14983:     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  14984:     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  14985:   }
1.203     brouard  14986:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  14987:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  14988:   /* Third parameter line */
                   14989:   while(fgets(line, MAXLINE, ficpar)) {
                   14990:     /* If line starts with a # it is a comment */
                   14991:     if (line[0] == '#') {
                   14992:       numlinepar++;
1.283     brouard  14993:       printf("%s",line);
                   14994:       fprintf(ficres,"%s",line);
                   14995:       fprintf(ficparo,"%s",line);
                   14996:       fprintf(ficlog,"%s",line);
1.197     brouard  14997:       continue;
                   14998:     }else
                   14999:       break;
                   15000:   }
1.351     brouard  15001:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   15002:     if (num_filled != 1){
                   15003:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15004:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15005:       model[0]='\0';
                   15006:       goto end;
                   15007:     }else{
                   15008:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   15009:       strcpy(line, linetmp);
                   15010:     }
                   15011:   }
                   15012:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  15013:     if (num_filled != 1){
1.302     brouard  15014:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15015:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  15016:       model[0]='\0';
                   15017:       goto end;
                   15018:     }
                   15019:     else{
                   15020:       if (model[0]=='+'){
                   15021:        for(i=1; i<=strlen(model);i++)
                   15022:          modeltemp[i-1]=model[i];
1.201     brouard  15023:        strcpy(model,modeltemp); 
1.197     brouard  15024:       }
                   15025:     }
1.338     brouard  15026:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  15027:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  15028:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   15029:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   15030:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  15031:   }
                   15032:   /* 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); */
                   15033:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   15034:   /* 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  15035:   /* 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); */
                   15036:   /* 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  15037:   fflush(ficlog);
1.190     brouard  15038:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   15039:   if(model[0]=='#'){
1.279     brouard  15040:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   15041:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   15042:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  15043:     if(mle != -1){
1.279     brouard  15044:       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  15045:       exit(1);
                   15046:     }
                   15047:   }
1.126     brouard  15048:   while((c=getc(ficpar))=='#' && c!= EOF){
                   15049:     ungetc(c,ficpar);
                   15050:     fgets(line, MAXLINE, ficpar);
                   15051:     numlinepar++;
1.195     brouard  15052:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   15053:       z[0]=line[1];
1.342     brouard  15054:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  15055:       debugILK=1;printf("DebugILK\n");
1.195     brouard  15056:     }
                   15057:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  15058:     fputs(line, stdout);
                   15059:     //puts(line);
1.126     brouard  15060:     fputs(line,ficparo);
                   15061:     fputs(line,ficlog);
                   15062:   }
                   15063:   ungetc(c,ficpar);
                   15064: 
                   15065:    
1.290     brouard  15066:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   15067:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   15068:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  15069:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   15070:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  15071:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   15072:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   15073:      v1+v2*age+v2*v3 makes cptcovn = 3
                   15074:   */
                   15075:   if (strlen(model)>1) 
1.187     brouard  15076:     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  15077:   else
1.187     brouard  15078:     ncovmodel=2; /* Constant and age */
1.133     brouard  15079:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   15080:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  15081:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   15082:     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);
                   15083:     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);
                   15084:     fflush(stdout);
                   15085:     fclose (ficlog);
                   15086:     goto end;
                   15087:   }
1.126     brouard  15088:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15089:   delti=delti3[1][1];
                   15090:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   15091:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  15092: /* We could also provide initial parameters values giving by simple logistic regression 
                   15093:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   15094:       /* for(i=1;i<nlstate;i++){ */
                   15095:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15096:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15097:       /* } */
1.126     brouard  15098:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  15099:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   15100:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15101:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15102:     fclose (ficparo);
                   15103:     fclose (ficlog);
                   15104:     goto end;
                   15105:     exit(0);
1.220     brouard  15106:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  15107:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  15108:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   15109:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15110:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15111:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15112:     hess=matrix(1,npar,1,npar);
1.220     brouard  15113:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  15114:     /* Read guessed parameters */
1.126     brouard  15115:     /* Reads comments: lines beginning with '#' */
                   15116:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15117:       ungetc(c,ficpar);
                   15118:       fgets(line, MAXLINE, ficpar);
                   15119:       numlinepar++;
1.141     brouard  15120:       fputs(line,stdout);
1.126     brouard  15121:       fputs(line,ficparo);
                   15122:       fputs(line,ficlog);
                   15123:     }
                   15124:     ungetc(c,ficpar);
                   15125:     
                   15126:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  15127:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  15128:     for(i=1; i <=nlstate; i++){
1.234     brouard  15129:       j=0;
1.126     brouard  15130:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  15131:        if(jj==i) continue;
                   15132:        j++;
1.292     brouard  15133:        while((c=getc(ficpar))=='#' && c!= EOF){
                   15134:          ungetc(c,ficpar);
                   15135:          fgets(line, MAXLINE, ficpar);
                   15136:          numlinepar++;
                   15137:          fputs(line,stdout);
                   15138:          fputs(line,ficparo);
                   15139:          fputs(line,ficlog);
                   15140:        }
                   15141:        ungetc(c,ficpar);
1.234     brouard  15142:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15143:        if ((i1 != i) || (j1 != jj)){
                   15144:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  15145: It might be a problem of design; if ncovcol and the model are correct\n \
                   15146: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  15147:          exit(1);
                   15148:        }
                   15149:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15150:        if(mle==1)
                   15151:          printf("%1d%1d",i,jj);
                   15152:        fprintf(ficlog,"%1d%1d",i,jj);
                   15153:        for(k=1; k<=ncovmodel;k++){
                   15154:          fscanf(ficpar," %lf",&param[i][j][k]);
                   15155:          if(mle==1){
                   15156:            printf(" %lf",param[i][j][k]);
                   15157:            fprintf(ficlog," %lf",param[i][j][k]);
                   15158:          }
                   15159:          else
                   15160:            fprintf(ficlog," %lf",param[i][j][k]);
                   15161:          fprintf(ficparo," %lf",param[i][j][k]);
                   15162:        }
                   15163:        fscanf(ficpar,"\n");
                   15164:        numlinepar++;
                   15165:        if(mle==1)
                   15166:          printf("\n");
                   15167:        fprintf(ficlog,"\n");
                   15168:        fprintf(ficparo,"\n");
1.126     brouard  15169:       }
                   15170:     }  
                   15171:     fflush(ficlog);
1.234     brouard  15172:     
1.251     brouard  15173:     /* Reads parameters values */
1.126     brouard  15174:     p=param[1][1];
1.251     brouard  15175:     pstart=paramstart[1][1];
1.126     brouard  15176:     
                   15177:     /* Reads comments: lines beginning with '#' */
                   15178:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15179:       ungetc(c,ficpar);
                   15180:       fgets(line, MAXLINE, ficpar);
                   15181:       numlinepar++;
1.141     brouard  15182:       fputs(line,stdout);
1.126     brouard  15183:       fputs(line,ficparo);
                   15184:       fputs(line,ficlog);
                   15185:     }
                   15186:     ungetc(c,ficpar);
                   15187: 
                   15188:     for(i=1; i <=nlstate; i++){
                   15189:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  15190:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15191:        if ( (i1-i) * (j1-j) != 0){
                   15192:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   15193:          exit(1);
                   15194:        }
                   15195:        printf("%1d%1d",i,j);
                   15196:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15197:        fprintf(ficlog,"%1d%1d",i1,j1);
                   15198:        for(k=1; k<=ncovmodel;k++){
                   15199:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   15200:          printf(" %le",delti3[i][j][k]);
                   15201:          fprintf(ficparo," %le",delti3[i][j][k]);
                   15202:          fprintf(ficlog," %le",delti3[i][j][k]);
                   15203:        }
                   15204:        fscanf(ficpar,"\n");
                   15205:        numlinepar++;
                   15206:        printf("\n");
                   15207:        fprintf(ficparo,"\n");
                   15208:        fprintf(ficlog,"\n");
1.126     brouard  15209:       }
                   15210:     }
                   15211:     fflush(ficlog);
1.234     brouard  15212:     
1.145     brouard  15213:     /* Reads covariance matrix */
1.126     brouard  15214:     delti=delti3[1][1];
1.220     brouard  15215:                
                   15216:                
1.126     brouard  15217:     /* 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  15218:                
1.126     brouard  15219:     /* Reads comments: lines beginning with '#' */
                   15220:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15221:       ungetc(c,ficpar);
                   15222:       fgets(line, MAXLINE, ficpar);
                   15223:       numlinepar++;
1.141     brouard  15224:       fputs(line,stdout);
1.126     brouard  15225:       fputs(line,ficparo);
                   15226:       fputs(line,ficlog);
                   15227:     }
                   15228:     ungetc(c,ficpar);
1.220     brouard  15229:                
1.126     brouard  15230:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15231:     hess=matrix(1,npar,1,npar);
1.131     brouard  15232:     for(i=1; i <=npar; i++)
                   15233:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  15234:                
1.194     brouard  15235:     /* Scans npar lines */
1.126     brouard  15236:     for(i=1; i <=npar; i++){
1.226     brouard  15237:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  15238:       if(count != 3){
1.226     brouard  15239:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15240: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15241: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15242:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15243: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15244: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15245:        exit(1);
1.220     brouard  15246:       }else{
1.226     brouard  15247:        if(mle==1)
                   15248:          printf("%1d%1d%d",i1,j1,jk);
                   15249:       }
                   15250:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   15251:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  15252:       for(j=1; j <=i; j++){
1.226     brouard  15253:        fscanf(ficpar," %le",&matcov[i][j]);
                   15254:        if(mle==1){
                   15255:          printf(" %.5le",matcov[i][j]);
                   15256:        }
                   15257:        fprintf(ficlog," %.5le",matcov[i][j]);
                   15258:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  15259:       }
                   15260:       fscanf(ficpar,"\n");
                   15261:       numlinepar++;
                   15262:       if(mle==1)
1.220     brouard  15263:                                printf("\n");
1.126     brouard  15264:       fprintf(ficlog,"\n");
                   15265:       fprintf(ficparo,"\n");
                   15266:     }
1.194     brouard  15267:     /* End of read covariance matrix npar lines */
1.126     brouard  15268:     for(i=1; i <=npar; i++)
                   15269:       for(j=i+1;j<=npar;j++)
1.226     brouard  15270:        matcov[i][j]=matcov[j][i];
1.126     brouard  15271:     
                   15272:     if(mle==1)
                   15273:       printf("\n");
                   15274:     fprintf(ficlog,"\n");
                   15275:     
                   15276:     fflush(ficlog);
                   15277:     
                   15278:   }    /* End of mle != -3 */
1.218     brouard  15279:   
1.186     brouard  15280:   /*  Main data
                   15281:    */
1.290     brouard  15282:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   15283:   /* num=lvector(1,n); */
                   15284:   /* moisnais=vector(1,n); */
                   15285:   /* annais=vector(1,n); */
                   15286:   /* moisdc=vector(1,n); */
                   15287:   /* andc=vector(1,n); */
                   15288:   /* weight=vector(1,n); */
                   15289:   /* agedc=vector(1,n); */
                   15290:   /* cod=ivector(1,n); */
                   15291:   /* for(i=1;i<=n;i++){ */
                   15292:   num=lvector(firstobs,lastobs);
                   15293:   moisnais=vector(firstobs,lastobs);
                   15294:   annais=vector(firstobs,lastobs);
                   15295:   moisdc=vector(firstobs,lastobs);
                   15296:   andc=vector(firstobs,lastobs);
                   15297:   weight=vector(firstobs,lastobs);
                   15298:   agedc=vector(firstobs,lastobs);
                   15299:   cod=ivector(firstobs,lastobs);
                   15300:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  15301:     num[i]=0;
                   15302:     moisnais[i]=0;
                   15303:     annais[i]=0;
                   15304:     moisdc[i]=0;
                   15305:     andc[i]=0;
                   15306:     agedc[i]=0;
                   15307:     cod[i]=0;
                   15308:     weight[i]=1.0; /* Equal weights, 1 by default */
                   15309:   }
1.290     brouard  15310:   mint=matrix(1,maxwav,firstobs,lastobs);
                   15311:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  15312:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  15313:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  15314:   tab=ivector(1,NCOVMAX);
1.144     brouard  15315:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  15316:   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  15317: 
1.136     brouard  15318:   /* Reads data from file datafile */
                   15319:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   15320:     goto end;
                   15321: 
                   15322:   /* Calculation of the number of parameters from char model */
1.234     brouard  15323:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  15324:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   15325:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   15326:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   15327:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  15328:   */
                   15329:   
                   15330:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   15331:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  15332:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  15333:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  15334:   TvarsD=ivector(1,NCOVMAX); /*  */
                   15335:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   15336:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  15337:   TvarF=ivector(1,NCOVMAX); /*  */
                   15338:   TvarFind=ivector(1,NCOVMAX); /*  */
                   15339:   TvarV=ivector(1,NCOVMAX); /*  */
                   15340:   TvarVind=ivector(1,NCOVMAX); /*  */
                   15341:   TvarA=ivector(1,NCOVMAX); /*  */
                   15342:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15343:   TvarFD=ivector(1,NCOVMAX); /*  */
                   15344:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   15345:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   15346:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   15347:   TvarVD=ivector(1,NCOVMAX); /*  */
                   15348:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   15349:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   15350:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  15351:   TvarVV=ivector(1,NCOVMAX); /*  */
                   15352:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  15353:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   15354:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   15355:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   15356:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15357: 
1.230     brouard  15358:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  15359:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  15360:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   15361:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   15362:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  15363:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15364:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15365: 
1.137     brouard  15366:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   15367:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   15368:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   15369:   */
                   15370:   /* For model-covariate k tells which data-covariate to use but
                   15371:     because this model-covariate is a construction we invent a new column
                   15372:     ncovcol + k1
                   15373:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   15374:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  15375:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   15376:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  15377:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   15378:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  15379:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  15380:   */
1.145     brouard  15381:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   15382:   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  15383:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   15384:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  15385:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  15386:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  15387:                         4 covariates (3 plus signs)
                   15388:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  15389:                           */  
                   15390:   for(i=1;i<NCOVMAX;i++)
                   15391:     Tage[i]=0;
1.230     brouard  15392:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  15393:                                * individual dummy, fixed or varying:
                   15394:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   15395:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  15396:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   15397:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   15398:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   15399:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   15400:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  15401:                                * individual quantitative, fixed or varying:
                   15402:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   15403:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   15404:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  15405: 
                   15406: /* Probably useless zeroes */
                   15407:   for(i=1;i<NCOVMAX;i++){
                   15408:     DummyV[i]=0;
                   15409:     FixedV[i]=0;
                   15410:   }
                   15411: 
                   15412:   for(i=1; i <=ncovcol;i++){
                   15413:     DummyV[i]=0;
                   15414:     FixedV[i]=0;
                   15415:   }
                   15416:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   15417:     DummyV[i]=1;
                   15418:     FixedV[i]=0;
                   15419:   }
                   15420:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   15421:     DummyV[i]=0;
                   15422:     FixedV[i]=1;
                   15423:   }
                   15424:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15425:     DummyV[i]=1;
                   15426:     FixedV[i]=1;
                   15427:   }
                   15428:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15429:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15430:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15431:   }
                   15432: 
                   15433: 
                   15434: 
1.186     brouard  15435: /* Main decodemodel */
                   15436: 
1.187     brouard  15437: 
1.223     brouard  15438:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  15439:     goto end;
                   15440: 
1.137     brouard  15441:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   15442:     nbwarn++;
                   15443:     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); 
                   15444:     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); 
                   15445:   }
1.136     brouard  15446:     /*  if(mle==1){*/
1.137     brouard  15447:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   15448:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  15449:   }
                   15450: 
                   15451:     /*-calculation of age at interview from date of interview and age at death -*/
                   15452:   agev=matrix(1,maxwav,1,imx);
                   15453: 
                   15454:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   15455:     goto end;
                   15456: 
1.126     brouard  15457: 
1.136     brouard  15458:   agegomp=(int)agemin;
1.290     brouard  15459:   free_vector(moisnais,firstobs,lastobs);
                   15460:   free_vector(annais,firstobs,lastobs);
1.126     brouard  15461:   /* free_matrix(mint,1,maxwav,1,n);
                   15462:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  15463:   /* free_vector(moisdc,1,n); */
                   15464:   /* free_vector(andc,1,n); */
1.145     brouard  15465:   /* */
                   15466:   
1.126     brouard  15467:   wav=ivector(1,imx);
1.214     brouard  15468:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15469:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15470:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15471:   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.*/
                   15472:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   15473:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  15474:    
                   15475:   /* Concatenates waves */
1.214     brouard  15476:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   15477:      Death is a valid wave (if date is known).
                   15478:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   15479:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   15480:      and mw[mi+1][i]. dh depends on stepm.
                   15481:   */
                   15482: 
1.126     brouard  15483:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  15484:   /* Concatenates waves */
1.145     brouard  15485:  
1.290     brouard  15486:   free_vector(moisdc,firstobs,lastobs);
                   15487:   free_vector(andc,firstobs,lastobs);
1.215     brouard  15488: 
1.126     brouard  15489:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   15490:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   15491:   ncodemax[1]=1;
1.145     brouard  15492:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  15493:   cptcoveff=0;
1.220     brouard  15494:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  15495:     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  15496:   }
                   15497:   
                   15498:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  15499:   invalidvarcomb=ivector(0, ncovcombmax); 
                   15500:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  15501:     invalidvarcomb[i]=0;
                   15502:   
1.211     brouard  15503:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  15504:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  15505:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  15506:   
1.200     brouard  15507:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  15508:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  15509:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  15510:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   15511:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   15512:    * (currently 0 or 1) in the data.
                   15513:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   15514:    * corresponding modality (h,j).
                   15515:    */
                   15516: 
1.145     brouard  15517:   h=0;
                   15518:   /*if (cptcovn > 0) */
1.126     brouard  15519:   m=pow(2,cptcoveff);
                   15520:  
1.144     brouard  15521:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  15522:           * For k=4 covariates, h goes from 1 to m=2**k
                   15523:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   15524:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  15525:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   15526:           *______________________________   *______________________
                   15527:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   15528:           *     2     2     1     1     1   *     1     0  0  0  1 
                   15529:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   15530:           *     4     2     2     1     1   *     3     0  0  1  1 
                   15531:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   15532:           *     6     2     1     2     1   *     5     0  1  0  1 
                   15533:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   15534:           *     8     2     2     2     1   *     7     0  1  1  1 
                   15535:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   15536:           *    10     2     1     1     2   *     9     1  0  0  1 
                   15537:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   15538:           *    12     2     2     1     2   *    11     1  0  1  1 
                   15539:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   15540:           *    14     2     1     2     2   *    13     1  1  0  1 
                   15541:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   15542:           *    16     2     2     2     2   *    15     1  1  1  1          
                   15543:           */                                     
1.212     brouard  15544:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  15545:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   15546:      * and the value of each covariate?
                   15547:      * V1=1, V2=1, V3=2, V4=1 ?
                   15548:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   15549:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   15550:      * In order to get the real value in the data, we use nbcode
                   15551:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   15552:      * We are keeping this crazy system in order to be able (in the future?) 
                   15553:      * to have more than 2 values (0 or 1) for a covariate.
                   15554:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   15555:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   15556:      *              bbbbbbbb
                   15557:      *              76543210     
                   15558:      *   h-1        00000101 (6-1=5)
1.219     brouard  15559:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  15560:      *           &
                   15561:      *     1        00000001 (1)
1.219     brouard  15562:      *              00000000        = 1 & ((h-1) >> (k-1))
                   15563:      *          +1= 00000001 =1 
1.211     brouard  15564:      *
                   15565:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   15566:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   15567:      *    >>k'            11
                   15568:      *          &   00000001
                   15569:      *            = 00000001
                   15570:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   15571:      * Reverse h=6 and m=16?
                   15572:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   15573:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   15574:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   15575:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   15576:      * V3=decodtabm(14,3,2**4)=2
                   15577:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   15578:      *(h-1) >> (j-1)    0011 =13 >> 2
                   15579:      *          &1 000000001
                   15580:      *           = 000000001
                   15581:      *         +1= 000000010 =2
                   15582:      *                  2211
                   15583:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   15584:      *                  V3=2
1.220     brouard  15585:                 * codtabm and decodtabm are identical
1.211     brouard  15586:      */
                   15587: 
1.145     brouard  15588: 
                   15589:  free_ivector(Ndum,-1,NCOVMAX);
                   15590: 
                   15591: 
1.126     brouard  15592:     
1.186     brouard  15593:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  15594:   strcpy(optionfilegnuplot,optionfilefiname);
                   15595:   if(mle==-3)
1.201     brouard  15596:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  15597:   strcat(optionfilegnuplot,".gp");
                   15598: 
                   15599:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   15600:     printf("Problem with file %s",optionfilegnuplot);
                   15601:   }
                   15602:   else{
1.204     brouard  15603:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  15604:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  15605:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   15606:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  15607:   }
                   15608:   /*  fclose(ficgp);*/
1.186     brouard  15609: 
                   15610: 
                   15611:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  15612: 
                   15613:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   15614:   if(mle==-3)
1.201     brouard  15615:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  15616:   strcat(optionfilehtm,".htm");
                   15617:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  15618:     printf("Problem with %s \n",optionfilehtm);
                   15619:     exit(0);
1.126     brouard  15620:   }
                   15621: 
                   15622:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   15623:   strcat(optionfilehtmcov,"-cov.htm");
                   15624:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   15625:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   15626:   }
                   15627:   else{
                   15628:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   15629: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15630: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  15631:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   15632:   }
                   15633: 
1.335     brouard  15634:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   15635: <title>IMaCh %s</title></head>\n\
                   15636:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   15637: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   15638: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   15639: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   15640: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   15641:   
                   15642:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15643: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  15644: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  15645: 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  15646: \n\
                   15647: <hr  size=\"2\" color=\"#EC5E5E\">\
                   15648:  <ul><li><h4>Parameter files</h4>\n\
                   15649:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   15650:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   15651:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   15652:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   15653:  - Date and time at start: %s</ul>\n",\
1.335     brouard  15654:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  15655:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   15656:          fileres,fileres,\
                   15657:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   15658:   fflush(fichtm);
                   15659: 
                   15660:   strcpy(pathr,path);
                   15661:   strcat(pathr,optionfilefiname);
1.184     brouard  15662: #ifdef WIN32
                   15663:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   15664: #else
1.126     brouard  15665:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  15666: #endif
                   15667:          
1.126     brouard  15668:   
1.220     brouard  15669:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   15670:                 and for any valid combination of covariates
1.126     brouard  15671:      and prints on file fileres'p'. */
1.359     brouard  15672:   freqsummary(fileres, p, pstart, (double)agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  15673:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  15674: 
                   15675:   fprintf(fichtm,"\n");
1.286     brouard  15676:   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  15677:          ftol, stepm);
                   15678:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   15679:   ncurrv=1;
                   15680:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   15681:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   15682:   ncurrv=i;
                   15683:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15684:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  15685:   ncurrv=i;
                   15686:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15687:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  15688:   ncurrv=i;
                   15689:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   15690:   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", \
                   15691:           nlstate, ndeath, maxwav, mle, weightopt);
                   15692: 
                   15693:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   15694: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   15695: 
                   15696:   
1.317     brouard  15697:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  15698: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   15699: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  15700:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  15701:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  15702:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15703:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15704:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15705:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  15706: 
1.126     brouard  15707:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   15708:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   15709:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   15710: 
                   15711:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  15712:   /* For mortality only */
1.126     brouard  15713:   if (mle==-3){
1.136     brouard  15714:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  15715:     for(i=1;i<=NDIM;i++)
                   15716:       for(j=1;j<=NDIM;j++)
                   15717:        ximort[i][j]=0.;
1.186     brouard  15718:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  15719:     cens=ivector(firstobs,lastobs);
                   15720:     ageexmed=vector(firstobs,lastobs);
                   15721:     agecens=vector(firstobs,lastobs);
                   15722:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  15723:                
1.126     brouard  15724:     for (i=1; i<=imx; i++){
                   15725:       dcwave[i]=-1;
                   15726:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  15727:        if (s[m][i]>nlstate) {
                   15728:          dcwave[i]=m;
                   15729:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   15730:          break;
                   15731:        }
1.126     brouard  15732:     }
1.226     brouard  15733:     
1.126     brouard  15734:     for (i=1; i<=imx; i++) {
                   15735:       if (wav[i]>0){
1.226     brouard  15736:        ageexmed[i]=agev[mw[1][i]][i];
                   15737:        j=wav[i];
                   15738:        agecens[i]=1.; 
                   15739:        
                   15740:        if (ageexmed[i]> 1 && wav[i] > 0){
                   15741:          agecens[i]=agev[mw[j][i]][i];
                   15742:          cens[i]= 1;
                   15743:        }else if (ageexmed[i]< 1) 
                   15744:          cens[i]= -1;
                   15745:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   15746:          cens[i]=0 ;
1.126     brouard  15747:       }
                   15748:       else cens[i]=-1;
                   15749:     }
                   15750:     
                   15751:     for (i=1;i<=NDIM;i++) {
                   15752:       for (j=1;j<=NDIM;j++)
1.226     brouard  15753:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  15754:     }
                   15755:     
1.302     brouard  15756:     p[1]=0.0268; p[NDIM]=0.083;
                   15757:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  15758:     
                   15759:     
1.136     brouard  15760: #ifdef GSL
                   15761:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  15762: #else
1.359     brouard  15763:     printf("Powell-mort\n");  fprintf(ficlog,"Powell-mort\n");
1.136     brouard  15764: #endif
1.201     brouard  15765:     strcpy(filerespow,"POW-MORT_"); 
                   15766:     strcat(filerespow,fileresu);
1.126     brouard  15767:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   15768:       printf("Problem with resultfile: %s\n", filerespow);
                   15769:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   15770:     }
1.136     brouard  15771: #ifdef GSL
                   15772:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  15773: #else
1.126     brouard  15774:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  15775: #endif
1.126     brouard  15776:     /*  for (i=1;i<=nlstate;i++)
                   15777:        for(j=1;j<=nlstate+ndeath;j++)
                   15778:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   15779:     */
                   15780:     fprintf(ficrespow,"\n");
1.136     brouard  15781: #ifdef GSL
                   15782:     /* gsl starts here */ 
                   15783:     T = gsl_multimin_fminimizer_nmsimplex;
                   15784:     gsl_multimin_fminimizer *sfm = NULL;
                   15785:     gsl_vector *ss, *x;
                   15786:     gsl_multimin_function minex_func;
                   15787: 
                   15788:     /* Initial vertex size vector */
                   15789:     ss = gsl_vector_alloc (NDIM);
                   15790:     
                   15791:     if (ss == NULL){
                   15792:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   15793:     }
                   15794:     /* Set all step sizes to 1 */
                   15795:     gsl_vector_set_all (ss, 0.001);
                   15796: 
                   15797:     /* Starting point */
1.126     brouard  15798:     
1.136     brouard  15799:     x = gsl_vector_alloc (NDIM);
                   15800:     
                   15801:     if (x == NULL){
                   15802:       gsl_vector_free(ss);
                   15803:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   15804:     }
                   15805:   
                   15806:     /* Initialize method and iterate */
                   15807:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  15808:     /*     gsl_vector_set(x, 0, 0.0268); */
                   15809:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  15810:     gsl_vector_set(x, 0, p[1]);
                   15811:     gsl_vector_set(x, 1, p[2]);
                   15812: 
                   15813:     minex_func.f = &gompertz_f;
                   15814:     minex_func.n = NDIM;
                   15815:     minex_func.params = (void *)&p; /* ??? */
                   15816:     
                   15817:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   15818:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   15819:     
                   15820:     printf("Iterations beginning .....\n\n");
                   15821:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   15822: 
                   15823:     iteri=0;
                   15824:     while (rval == GSL_CONTINUE){
                   15825:       iteri++;
                   15826:       status = gsl_multimin_fminimizer_iterate(sfm);
                   15827:       
                   15828:       if (status) printf("error: %s\n", gsl_strerror (status));
                   15829:       fflush(0);
                   15830:       
                   15831:       if (status) 
                   15832:         break;
                   15833:       
                   15834:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   15835:       ssval = gsl_multimin_fminimizer_size (sfm);
                   15836:       
                   15837:       if (rval == GSL_SUCCESS)
                   15838:         printf ("converged to a local maximum at\n");
                   15839:       
                   15840:       printf("%5d ", iteri);
                   15841:       for (it = 0; it < NDIM; it++){
                   15842:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   15843:       }
                   15844:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   15845:     }
                   15846:     
                   15847:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   15848:     
                   15849:     gsl_vector_free(x); /* initial values */
                   15850:     gsl_vector_free(ss); /* inital step size */
                   15851:     for (it=0; it<NDIM; it++){
                   15852:       p[it+1]=gsl_vector_get(sfm->x,it);
                   15853:       fprintf(ficrespow," %.12lf", p[it]);
                   15854:     }
                   15855:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   15856: #endif
                   15857: #ifdef POWELL
1.361     brouard  15858: #ifdef LINMINORIGINAL
                   15859: #else /* LINMINORIGINAL */
                   15860:   
                   15861:   flatdir=ivector(1,npar); 
                   15862:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   15863: #endif /*LINMINORIGINAL */
1.362     brouard  15864:     /* powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz); */
                   15865:   /* double h0=0.25; */
                   15866:   macheps=pow(16.0,-13.0);
                   15867:   printf("Praxis Gegenfurtner mle=%d\n",mle);
                   15868:   fprintf(ficlog, "Praxis  Gegenfurtner mle=%d\n", mle);fflush(ficlog);
                   15869:    /* ffmin = praxis(ftol,macheps, h0, npar, prin, p, gompertz); */
                   15870:   /* For the Gompertz we use only two parameters */
                   15871:   int _npar=2;
                   15872:    ffmin = praxis(ftol,macheps, h0, _npar, 4, p, gompertz);
                   15873:   printf("End Praxis\n");
1.126     brouard  15874:     fclose(ficrespow);
1.361     brouard  15875: #ifdef LINMINORIGINAL
                   15876: #else
                   15877:       free_ivector(flatdir,1,npar); 
                   15878: #endif  /* LINMINORIGINAL*/
1.126     brouard  15879:     
1.203     brouard  15880:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  15881: 
                   15882:     for(i=1; i <=NDIM; i++)
                   15883:       for(j=i+1;j<=NDIM;j++)
1.359     brouard  15884:        matcov[i][j]=matcov[j][i];
1.126     brouard  15885:     
                   15886:     printf("\nCovariance matrix\n ");
1.203     brouard  15887:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  15888:     for(i=1; i <=NDIM; i++) {
                   15889:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  15890:                                printf("%f ",matcov[i][j]);
                   15891:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  15892:       }
1.203     brouard  15893:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  15894:     }
                   15895:     
                   15896:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  15897:     for (i=1;i<=NDIM;i++) {
1.126     brouard  15898:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  15899:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   15900:     }
1.302     brouard  15901:     lsurv=vector(agegomp,AGESUP);
                   15902:     lpop=vector(agegomp,AGESUP);
                   15903:     tpop=vector(agegomp,AGESUP);
1.126     brouard  15904:     lsurv[agegomp]=100000;
                   15905:     
                   15906:     for (k=agegomp;k<=AGESUP;k++) {
                   15907:       agemortsup=k;
                   15908:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   15909:     }
                   15910:     
                   15911:     for (k=agegomp;k<agemortsup;k++)
                   15912:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   15913:     
                   15914:     for (k=agegomp;k<agemortsup;k++){
                   15915:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   15916:       sumlpop=sumlpop+lpop[k];
                   15917:     }
                   15918:     
                   15919:     tpop[agegomp]=sumlpop;
                   15920:     for (k=agegomp;k<(agemortsup-3);k++){
                   15921:       /*  tpop[k+1]=2;*/
                   15922:       tpop[k+1]=tpop[k]-lpop[k];
                   15923:     }
                   15924:     
                   15925:     
                   15926:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   15927:     for (k=agegomp;k<(agemortsup-2);k++) 
                   15928:       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]);
                   15929:     
                   15930:     
                   15931:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  15932:                ageminpar=50;
                   15933:                agemaxpar=100;
1.194     brouard  15934:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   15935:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15936: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15937: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15938:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15939: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15940: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  15941:     }else{
                   15942:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   15943:                        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  15944:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  15945:                }
1.201     brouard  15946:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  15947:                     stepm, weightopt,\
                   15948:                     model,imx,p,matcov,agemortsup);
                   15949:     
1.302     brouard  15950:     free_vector(lsurv,agegomp,AGESUP);
                   15951:     free_vector(lpop,agegomp,AGESUP);
                   15952:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  15953:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  15954:     free_ivector(dcwave,firstobs,lastobs);
                   15955:     free_vector(agecens,firstobs,lastobs);
                   15956:     free_vector(ageexmed,firstobs,lastobs);
                   15957:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  15958: #ifdef GSL
1.136     brouard  15959: #endif
1.186     brouard  15960:   } /* Endof if mle==-3 mortality only */
1.205     brouard  15961:   /* Standard  */
                   15962:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   15963:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15964:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  15965:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  15966:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   15967:     for (k=1; k<=npar;k++)
                   15968:       printf(" %d %8.5f",k,p[k]);
                   15969:     printf("\n");
1.205     brouard  15970:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   15971:       /* mlikeli uses func not funcone */
1.247     brouard  15972:       /* for(i=1;i<nlstate;i++){ */
                   15973:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15974:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15975:       /* } */
1.205     brouard  15976:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   15977:     }
                   15978:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   15979:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15980:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   15981:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15982:     }
                   15983:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  15984:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15985:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  15986:           /* exit(0); */
1.126     brouard  15987:     for (k=1; k<=npar;k++)
                   15988:       printf(" %d %8.5f",k,p[k]);
                   15989:     printf("\n");
                   15990:     
                   15991:     /*--------- results files --------------*/
1.283     brouard  15992:     /* 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  15993:     
                   15994:     
                   15995:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15996:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  15997:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15998: 
                   15999:     printf("#model=  1      +     age ");
                   16000:     fprintf(ficres,"#model=  1      +     age ");
                   16001:     fprintf(ficlog,"#model=  1      +     age ");
                   16002:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   16003: </ul>", model);
                   16004: 
                   16005:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   16006:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16007:     if(nagesqr==1){
                   16008:       printf("  + age*age  ");
                   16009:       fprintf(ficres,"  + age*age  ");
                   16010:       fprintf(ficlog,"  + age*age  ");
                   16011:       fprintf(fichtm, "<th>+ age*age</th>");
                   16012:     }
1.362     brouard  16013:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16014:       if(Typevar[j]==0) {
                   16015:        printf("  +      V%d  ",Tvar[j]);
                   16016:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   16017:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   16018:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16019:       }else if(Typevar[j]==1) {
                   16020:        printf("  +    V%d*age ",Tvar[j]);
                   16021:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   16022:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   16023:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16024:       }else if(Typevar[j]==2) {
                   16025:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16026:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16027:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16028:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16029:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   16030:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16031:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16032:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16033:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16034:       }
                   16035:     }
                   16036:     printf("\n");
                   16037:     fprintf(ficres,"\n");
                   16038:     fprintf(ficlog,"\n");
                   16039:     fprintf(fichtm, "</tr>");
                   16040:     fprintf(fichtm, "\n");
                   16041:     
                   16042:     
1.126     brouard  16043:     for(i=1,jk=1; i <=nlstate; i++){
                   16044:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  16045:        if (k != i) {
1.319     brouard  16046:          fprintf(fichtm, "<tr>");
1.225     brouard  16047:          printf("%d%d ",i,k);
                   16048:          fprintf(ficlog,"%d%d ",i,k);
                   16049:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  16050:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16051:          for(j=1; j <=ncovmodel; j++){
                   16052:            printf("%12.7f ",p[jk]);
                   16053:            fprintf(ficlog,"%12.7f ",p[jk]);
                   16054:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  16055:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  16056:            jk++; 
                   16057:          }
                   16058:          printf("\n");
                   16059:          fprintf(ficlog,"\n");
                   16060:          fprintf(ficres,"\n");
1.319     brouard  16061:          fprintf(fichtm, "</tr>\n");
1.225     brouard  16062:        }
1.126     brouard  16063:       }
                   16064:     }
1.319     brouard  16065:     /* fprintf(fichtm,"</tr>\n"); */
                   16066:     fprintf(fichtm,"</table>\n");
                   16067:     fprintf(fichtm, "\n");
                   16068: 
1.203     brouard  16069:     if(mle != 0){
                   16070:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  16071:       ftolhess=ftol; /* Usually correct */
1.203     brouard  16072:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   16073:       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");
                   16074:       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  16075:       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  16076:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   16077:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16078:       if(nagesqr==1){
                   16079:        printf("  + age*age  ");
                   16080:        fprintf(ficres,"  + age*age  ");
                   16081:        fprintf(ficlog,"  + age*age  ");
                   16082:        fprintf(fichtm, "<th>+ age*age</th>");
                   16083:       }
1.362     brouard  16084:       for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16085:        if(Typevar[j]==0) {
                   16086:          printf("  +      V%d  ",Tvar[j]);
                   16087:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16088:        }else if(Typevar[j]==1) {
                   16089:          printf("  +    V%d*age ",Tvar[j]);
                   16090:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16091:        }else if(Typevar[j]==2) {
                   16092:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16093:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   16094:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16095:        }
                   16096:       }
                   16097:       fprintf(fichtm, "</tr>\n");
                   16098:  
1.203     brouard  16099:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  16100:        for(k=1; k <=(nlstate+ndeath); k++){
                   16101:          if (k != i) {
1.319     brouard  16102:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  16103:            printf("%d%d ",i,k);
                   16104:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  16105:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16106:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  16107:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  16108:              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]));
                   16109:              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  16110:              if(fabs(wald) > 1.96){
1.321     brouard  16111:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  16112:              }else{
                   16113:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   16114:              }
1.324     brouard  16115:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  16116:              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  16117:              jk++; 
                   16118:            }
                   16119:            printf("\n");
                   16120:            fprintf(ficlog,"\n");
1.319     brouard  16121:            fprintf(fichtm, "</tr>\n");
1.225     brouard  16122:          }
                   16123:        }
1.193     brouard  16124:       }
1.203     brouard  16125:     } /* end of hesscov and Wald tests */
1.319     brouard  16126:     fprintf(fichtm,"</table>\n");
1.225     brouard  16127:     
1.203     brouard  16128:     /*  */
1.126     brouard  16129:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   16130:     printf("# Scales (for hessian or gradient estimation)\n");
                   16131:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   16132:     for(i=1,jk=1; i <=nlstate; i++){
                   16133:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  16134:        if (j!=i) {
                   16135:          fprintf(ficres,"%1d%1d",i,j);
                   16136:          printf("%1d%1d",i,j);
                   16137:          fprintf(ficlog,"%1d%1d",i,j);
                   16138:          for(k=1; k<=ncovmodel;k++){
                   16139:            printf(" %.5e",delti[jk]);
                   16140:            fprintf(ficlog," %.5e",delti[jk]);
                   16141:            fprintf(ficres," %.5e",delti[jk]);
                   16142:            jk++;
                   16143:          }
                   16144:          printf("\n");
                   16145:          fprintf(ficlog,"\n");
                   16146:          fprintf(ficres,"\n");
                   16147:        }
1.126     brouard  16148:       }
                   16149:     }
                   16150:     
                   16151:     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
1.349     brouard  16152:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  16153:       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");
                   16154:     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");
                   16155:     /* # 121 Var(a12)\n\ */
                   16156:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   16157:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   16158:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   16159:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   16160:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   16161:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   16162:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   16163:     
                   16164:     
                   16165:     /* Just to have a covariance matrix which will be more understandable
                   16166:        even is we still don't want to manage dictionary of variables
                   16167:     */
                   16168:     for(itimes=1;itimes<=2;itimes++){
                   16169:       jj=0;
                   16170:       for(i=1; i <=nlstate; i++){
1.225     brouard  16171:        for(j=1; j <=nlstate+ndeath; j++){
                   16172:          if(j==i) continue;
                   16173:          for(k=1; k<=ncovmodel;k++){
                   16174:            jj++;
                   16175:            ca[0]= k+'a'-1;ca[1]='\0';
                   16176:            if(itimes==1){
                   16177:              if(mle>=1)
                   16178:                printf("#%1d%1d%d",i,j,k);
                   16179:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   16180:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   16181:            }else{
                   16182:              if(mle>=1)
                   16183:                printf("%1d%1d%d",i,j,k);
                   16184:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   16185:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   16186:            }
                   16187:            ll=0;
                   16188:            for(li=1;li <=nlstate; li++){
                   16189:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   16190:                if(lj==li) continue;
                   16191:                for(lk=1;lk<=ncovmodel;lk++){
                   16192:                  ll++;
                   16193:                  if(ll<=jj){
                   16194:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   16195:                    if(ll<jj){
                   16196:                      if(itimes==1){
                   16197:                        if(mle>=1)
                   16198:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16199:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16200:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16201:                      }else{
                   16202:                        if(mle>=1)
                   16203:                          printf(" %.5e",matcov[jj][ll]); 
                   16204:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   16205:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   16206:                      }
                   16207:                    }else{
                   16208:                      if(itimes==1){
                   16209:                        if(mle>=1)
                   16210:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   16211:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   16212:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   16213:                      }else{
                   16214:                        if(mle>=1)
                   16215:                          printf(" %.7e",matcov[jj][ll]); 
                   16216:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   16217:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   16218:                      }
                   16219:                    }
                   16220:                  }
                   16221:                } /* end lk */
                   16222:              } /* end lj */
                   16223:            } /* end li */
                   16224:            if(mle>=1)
                   16225:              printf("\n");
                   16226:            fprintf(ficlog,"\n");
                   16227:            fprintf(ficres,"\n");
                   16228:            numlinepar++;
                   16229:          } /* end k*/
                   16230:        } /*end j */
1.126     brouard  16231:       } /* end i */
                   16232:     } /* end itimes */
                   16233:     
                   16234:     fflush(ficlog);
                   16235:     fflush(ficres);
1.225     brouard  16236:     while(fgets(line, MAXLINE, ficpar)) {
                   16237:       /* If line starts with a # it is a comment */
                   16238:       if (line[0] == '#') {
                   16239:        numlinepar++;
                   16240:        fputs(line,stdout);
                   16241:        fputs(line,ficparo);
                   16242:        fputs(line,ficlog);
1.299     brouard  16243:        fputs(line,ficres);
1.225     brouard  16244:        continue;
                   16245:       }else
                   16246:        break;
                   16247:     }
                   16248:     
1.209     brouard  16249:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   16250:     /*   ungetc(c,ficpar); */
                   16251:     /*   fgets(line, MAXLINE, ficpar); */
                   16252:     /*   fputs(line,stdout); */
                   16253:     /*   fputs(line,ficparo); */
                   16254:     /* } */
                   16255:     /* ungetc(c,ficpar); */
1.126     brouard  16256:     
                   16257:     estepm=0;
1.209     brouard  16258:     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  16259:       
                   16260:       if (num_filled != 6) {
                   16261:        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);
                   16262:        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);
                   16263:        goto end;
                   16264:       }
                   16265:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   16266:     }
                   16267:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   16268:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   16269:     
1.209     brouard  16270:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  16271:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   16272:     if (fage <= 2) {
                   16273:       bage = ageminpar;
                   16274:       fage = agemaxpar;
                   16275:     }
                   16276:     
                   16277:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  16278:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   16279:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  16280:                
1.186     brouard  16281:     /* Other stuffs, more or less useful */    
1.254     brouard  16282:     while(fgets(line, MAXLINE, ficpar)) {
                   16283:       /* If line starts with a # it is a comment */
                   16284:       if (line[0] == '#') {
                   16285:        numlinepar++;
                   16286:        fputs(line,stdout);
                   16287:        fputs(line,ficparo);
                   16288:        fputs(line,ficlog);
1.299     brouard  16289:        fputs(line,ficres);
1.254     brouard  16290:        continue;
                   16291:       }else
                   16292:        break;
                   16293:     }
                   16294: 
                   16295:     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){
                   16296:       
                   16297:       if (num_filled != 7) {
                   16298:        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);
                   16299:        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);
                   16300:        goto end;
                   16301:       }
                   16302:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   16303:       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);
                   16304:       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);
                   16305:       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  16306:     }
1.254     brouard  16307: 
                   16308:     while(fgets(line, MAXLINE, ficpar)) {
                   16309:       /* If line starts with a # it is a comment */
                   16310:       if (line[0] == '#') {
                   16311:        numlinepar++;
                   16312:        fputs(line,stdout);
                   16313:        fputs(line,ficparo);
                   16314:        fputs(line,ficlog);
1.299     brouard  16315:        fputs(line,ficres);
1.254     brouard  16316:        continue;
                   16317:       }else
                   16318:        break;
1.126     brouard  16319:     }
                   16320:     
                   16321:     
                   16322:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   16323:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   16324:     
1.254     brouard  16325:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   16326:       if (num_filled != 1) {
                   16327:        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);
                   16328:        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);
                   16329:        goto end;
                   16330:       }
                   16331:       printf("pop_based=%d\n",popbased);
                   16332:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   16333:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   16334:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   16335:     }
                   16336:      
1.258     brouard  16337:     /* Results */
1.359     brouard  16338:     /* Value of covariate in each resultine will be computed (if product) and sorted according to model rank */
1.332     brouard  16339:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   16340:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  16341:     endishere=0;
1.258     brouard  16342:     nresult=0;
1.308     brouard  16343:     parameterline=0;
1.258     brouard  16344:     do{
                   16345:       if(!fgets(line, MAXLINE, ficpar)){
                   16346:        endishere=1;
1.308     brouard  16347:        parameterline=15;
1.258     brouard  16348:       }else if (line[0] == '#') {
                   16349:        /* If line starts with a # it is a comment */
1.254     brouard  16350:        numlinepar++;
                   16351:        fputs(line,stdout);
                   16352:        fputs(line,ficparo);
                   16353:        fputs(line,ficlog);
1.299     brouard  16354:        fputs(line,ficres);
1.254     brouard  16355:        continue;
1.258     brouard  16356:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   16357:        parameterline=11;
1.296     brouard  16358:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  16359:        parameterline=12;
1.307     brouard  16360:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  16361:        parameterline=13;
1.307     brouard  16362:       }
1.258     brouard  16363:       else{
                   16364:        parameterline=14;
1.254     brouard  16365:       }
1.308     brouard  16366:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  16367:       case 11:
1.296     brouard  16368:        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)){
                   16369:                  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  16370:          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);
                   16371:          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);
                   16372:          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);
                   16373:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  16374:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   16375:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  16376:           prvforecast = 1;
                   16377:        } 
                   16378:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  16379:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16380:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16381:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  16382:           prvforecast = 2;
                   16383:        }
                   16384:        else {
                   16385:          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);
                   16386:          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);
                   16387:          goto end;
1.258     brouard  16388:        }
1.254     brouard  16389:        break;
1.258     brouard  16390:       case 12:
1.296     brouard  16391:        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)){
                   16392:           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);
                   16393:          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);
                   16394:          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);
                   16395:          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);
                   16396:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  16397:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   16398:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  16399:           prvbackcast = 1;
                   16400:        } 
                   16401:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  16402:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16403:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16404:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  16405:           prvbackcast = 2;
                   16406:        }
                   16407:        else {
                   16408:          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);
                   16409:          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);
                   16410:          goto end;
1.258     brouard  16411:        }
1.230     brouard  16412:        break;
1.258     brouard  16413:       case 13:
1.332     brouard  16414:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  16415:        nresult++; /* Sum of resultlines */
1.342     brouard  16416:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  16417:        /* removefirstspace(&resultlineori); */
                   16418:        
                   16419:        if(strstr(resultlineori,"v") !=0){
                   16420:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   16421:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   16422:          return 1;
                   16423:        }
                   16424:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  16425:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  16426:        if(nresult > MAXRESULTLINESPONE-1){
                   16427:          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);
                   16428:          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  16429:          goto end;
                   16430:        }
1.332     brouard  16431:        
1.310     brouard  16432:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  16433:          fprintf(ficparo,"result: %s\n",resultline);
                   16434:          fprintf(ficres,"result: %s\n",resultline);
                   16435:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  16436:        } else
                   16437:          goto end;
1.307     brouard  16438:        break;
                   16439:       case 14:
                   16440:        printf("Error: Unknown command '%s'\n",line);
                   16441:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  16442:        if(line[0] == ' ' || line[0] == '\n'){
                   16443:          printf("It should not be an empty line '%s'\n",line);
                   16444:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   16445:        }         
1.307     brouard  16446:        if(ncovmodel >=2 && nresult==0 ){
                   16447:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   16448:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  16449:        }
1.307     brouard  16450:        /* goto end; */
                   16451:        break;
1.308     brouard  16452:       case 15:
                   16453:        printf("End of resultlines.\n");
                   16454:        fprintf(ficlog,"End of resultlines.\n");
                   16455:        break;
                   16456:       default: /* parameterline =0 */
1.307     brouard  16457:        nresult=1;
                   16458:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  16459:       } /* End switch parameterline */
                   16460:     }while(endishere==0); /* End do */
1.126     brouard  16461:     
1.230     brouard  16462:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  16463:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  16464:     
                   16465:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  16466:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  16467:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16468: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16469: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  16470:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16471: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16472: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  16473:     }else{
1.270     brouard  16474:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  16475:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   16476:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   16477:       if(prvforecast==1){
                   16478:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   16479:         jprojd=jproj1;
                   16480:         mprojd=mproj1;
                   16481:         anprojd=anproj1;
                   16482:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   16483:         jprojf=jproj2;
                   16484:         mprojf=mproj2;
                   16485:         anprojf=anproj2;
                   16486:       } else if(prvforecast == 2){
                   16487:         dateprojd=dateintmean;
                   16488:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   16489:         dateprojf=dateintmean+yrfproj;
                   16490:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   16491:       }
                   16492:       if(prvbackcast==1){
                   16493:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   16494:         jbackd=jback1;
                   16495:         mbackd=mback1;
                   16496:         anbackd=anback1;
                   16497:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   16498:         jbackf=jback2;
                   16499:         mbackf=mback2;
                   16500:         anbackf=anback2;
                   16501:       } else if(prvbackcast == 2){
                   16502:         datebackd=dateintmean;
                   16503:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   16504:         datebackf=dateintmean-yrbproj;
                   16505:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   16506:       }
                   16507:       
1.350     brouard  16508:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  16509:     }
                   16510:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  16511:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   16512:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  16513:                
1.225     brouard  16514:     /*------------ free_vector  -------------*/
                   16515:     /*  chdir(path); */
1.220     brouard  16516:                
1.215     brouard  16517:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   16518:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   16519:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   16520:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  16521:     free_lvector(num,firstobs,lastobs);
                   16522:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  16523:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   16524:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   16525:     fclose(ficparo);
                   16526:     fclose(ficres);
1.220     brouard  16527:                
                   16528:                
1.186     brouard  16529:     /* Other results (useful)*/
1.220     brouard  16530:                
                   16531:                
1.126     brouard  16532:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  16533:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   16534:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  16535:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  16536:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  16537:     fclose(ficrespl);
                   16538: 
                   16539:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  16540:     /*#include "hpijx.h"*/
1.332     brouard  16541:     /** 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?*/
                   16542:     /* calls hpxij with combination k */
1.180     brouard  16543:     hPijx(p, bage, fage);
1.145     brouard  16544:     fclose(ficrespij);
1.227     brouard  16545:     
1.220     brouard  16546:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  16547:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  16548:     k=1;
1.126     brouard  16549:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  16550:     
1.269     brouard  16551:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   16552:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16553:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  16554:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  16555:        for(k=1;k<=ncovcombmax;k++)
                   16556:          probs[i][j][k]=0.;
1.269     brouard  16557:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   16558:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  16559:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  16560:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16561:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  16562:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  16563:          for(k=1;k<=ncovcombmax;k++)
                   16564:            mobaverages[i][j][k]=0.;
1.219     brouard  16565:       mobaverage=mobaverages;
                   16566:       if (mobilav!=0) {
1.235     brouard  16567:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  16568:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  16569:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   16570:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   16571:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   16572:        }
1.269     brouard  16573:       } else if (mobilavproj !=0) {
1.235     brouard  16574:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  16575:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  16576:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   16577:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16578:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16579:        }
1.269     brouard  16580:       }else{
                   16581:        printf("Internal error moving average\n");
                   16582:        fflush(stdout);
                   16583:        exit(1);
1.219     brouard  16584:       }
                   16585:     }/* end if moving average */
1.227     brouard  16586:     
1.126     brouard  16587:     /*---------- Forecasting ------------------*/
1.296     brouard  16588:     if(prevfcast==1){ 
                   16589:       /*   /\*    if(stepm ==1){*\/ */
                   16590:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16591:       /*This done previously after freqsummary.*/
                   16592:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   16593:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   16594:       
                   16595:       /* } else if (prvforecast==2){ */
                   16596:       /*   /\*    if(stepm ==1){*\/ */
                   16597:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16598:       /* } */
                   16599:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   16600:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  16601:     }
1.269     brouard  16602: 
1.296     brouard  16603:     /* Prevbcasting */
                   16604:     if(prevbcast==1){
1.219     brouard  16605:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16606:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16607:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   16608: 
                   16609:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   16610: 
                   16611:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  16612: 
1.219     brouard  16613:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   16614:       fclose(ficresplb);
                   16615: 
1.222     brouard  16616:       hBijx(p, bage, fage, mobaverage);
                   16617:       fclose(ficrespijb);
1.219     brouard  16618: 
1.296     brouard  16619:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   16620:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   16621:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   16622:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   16623:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   16624:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   16625: 
                   16626:       
1.269     brouard  16627:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16628: 
                   16629:       
1.269     brouard  16630:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  16631:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16632:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16633:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  16634:     }    /* end  Prevbcasting */
1.268     brouard  16635:  
1.186     brouard  16636:  
                   16637:     /* ------ Other prevalence ratios------------ */
1.126     brouard  16638: 
1.215     brouard  16639:     free_ivector(wav,1,imx);
                   16640:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   16641:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   16642:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  16643:                
                   16644:                
1.127     brouard  16645:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  16646:                
1.201     brouard  16647:     strcpy(filerese,"E_");
                   16648:     strcat(filerese,fileresu);
1.126     brouard  16649:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   16650:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16651:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16652:     }
1.208     brouard  16653:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   16654:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  16655: 
                   16656:     pstamp(ficreseij);
1.219     brouard  16657:                
1.351     brouard  16658:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   16659:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  16660:     
1.351     brouard  16661:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   16662:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   16663:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   16664:       /*       continue; */
1.219     brouard  16665:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  16666:       printf("\n#****** ");
1.351     brouard  16667:       for(j=1;j<=cptcovs;j++){
                   16668:       /* for(j=1;j<=cptcoveff;j++) { */
                   16669:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16670:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16671:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16672:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  16673:       }
                   16674:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  16675:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   16676:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  16677:       }
                   16678:       fprintf(ficreseij,"******\n");
1.235     brouard  16679:       printf("******\n");
1.219     brouard  16680:       
                   16681:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16682:       oldm=oldms;savm=savms;
1.330     brouard  16683:       /* 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  16684:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  16685:       
1.219     brouard  16686:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  16687:     }
                   16688:     fclose(ficreseij);
1.208     brouard  16689:     printf("done evsij\n");fflush(stdout);
                   16690:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  16691: 
1.218     brouard  16692:                
1.227     brouard  16693:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  16694:     /* Should be moved in a function */                
1.201     brouard  16695:     strcpy(filerest,"T_");
                   16696:     strcat(filerest,fileresu);
1.127     brouard  16697:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   16698:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   16699:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   16700:     }
1.208     brouard  16701:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   16702:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  16703:     strcpy(fileresstde,"STDE_");
                   16704:     strcat(fileresstde,fileresu);
1.126     brouard  16705:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  16706:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   16707:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  16708:     }
1.227     brouard  16709:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   16710:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  16711: 
1.201     brouard  16712:     strcpy(filerescve,"CVE_");
                   16713:     strcat(filerescve,fileresu);
1.126     brouard  16714:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  16715:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   16716:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  16717:     }
1.227     brouard  16718:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   16719:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  16720: 
1.201     brouard  16721:     strcpy(fileresv,"V_");
                   16722:     strcat(fileresv,fileresu);
1.126     brouard  16723:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   16724:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16725:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16726:     }
1.227     brouard  16727:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   16728:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  16729: 
1.235     brouard  16730:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   16731:     if (cptcovn < 1){i1=1;}
                   16732:     
1.334     brouard  16733:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   16734:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   16735:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   16736:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   16737:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   16738:       /* */
                   16739:       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  16740:        continue;
1.359     brouard  16741:       printf("\n# model=1+age+%s \n#****** Result for:", model);  /* HERE model is empty */
                   16742:       fprintf(ficrest,"\n# model=1+age+%s \n#****** Result for:", model);
                   16743:       fprintf(ficlog,"\n# model=1+age+%s \n#****** Result for:", model);
1.334     brouard  16744:       /* It might not be a good idea to mix dummies and quantitative */
                   16745:       /* 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 *\/ */
                   16746:       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 */
                   16747:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   16748:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   16749:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   16750:         * (V5 is quanti) V4 and V3 are dummies
                   16751:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   16752:         *                                                              l=1 l=2
                   16753:         *                                                           k=1  1   1   0   0
                   16754:         *                                                           k=2  2   1   1   0
                   16755:         *                                                           k=3 [1] [2]  0   1
                   16756:         *                                                           k=4  2   2   1   1
                   16757:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   16758:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   16759:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   16760:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   16761:         */
                   16762:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   16763:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   16764: /* We give up with the combinations!! */
1.342     brouard  16765:        /* if(debugILK) */
                   16766:        /*   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  16767: 
                   16768:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.344     brouard  16769:          /* printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /\* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  *\/ */ /* TinvDoQresult[nres][Name of the variable] */
                   16770:          printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordered by the covariate values in the resultline  */
                   16771:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   16772:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  16773:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16774:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16775:          }else{
                   16776:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16777:          }
                   16778:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16779:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16780:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   16781:          /* For each selected (single) quantitative value */
1.337     brouard  16782:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16783:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16784:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  16785:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16786:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16787:          }else{
                   16788:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16789:          }
                   16790:        }else{
                   16791:          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 */
                   16792:          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 */
                   16793:          exit(1);
                   16794:        }
1.335     brouard  16795:       } /* End loop for each variable in the resultline */
1.334     brouard  16796:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   16797:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   16798:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16799:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16800:       /* }      */
1.208     brouard  16801:       fprintf(ficrest,"******\n");
1.227     brouard  16802:       fprintf(ficlog,"******\n");
                   16803:       printf("******\n");
1.208     brouard  16804:       
                   16805:       fprintf(ficresstdeij,"\n#****** ");
                   16806:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  16807:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   16808:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  16809:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  16810:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16811:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16812:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16813:       }
                   16814:       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  16815:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   16816:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  16817:       }        
1.208     brouard  16818:       fprintf(ficresstdeij,"******\n");
                   16819:       fprintf(ficrescveij,"******\n");
                   16820:       
                   16821:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  16822:       /* pstamp(ficresvij); */
1.225     brouard  16823:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  16824:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16825:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  16826:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  16827:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  16828:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  16829:       }        
1.208     brouard  16830:       fprintf(ficresvij,"******\n");
                   16831:       
                   16832:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16833:       oldm=oldms;savm=savms;
1.235     brouard  16834:       printf(" cvevsij ");
                   16835:       fprintf(ficlog, " cvevsij ");
                   16836:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  16837:       printf(" end cvevsij \n ");
                   16838:       fprintf(ficlog, " end cvevsij \n ");
                   16839:       
                   16840:       /*
                   16841:        */
                   16842:       /* goto endfree; */
                   16843:       
                   16844:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16845:       pstamp(ficrest);
                   16846:       
1.269     brouard  16847:       epj=vector(1,nlstate+1);
1.208     brouard  16848:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  16849:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   16850:        cptcod= 0; /* To be deleted */
1.360     brouard  16851:        printf("varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
                   16852:        fprintf(ficlog, "varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
1.361     brouard  16853:        /* Call to varevsij to get cov(e.i, e.j)= vareij[i][j][(int)age]=sum_h sum_k trgrad(h_p.i) V(theta) grad(k_p.k) Equation 20 */
                   16854:        /* Depending of popbased which changes the prevalences, either cross-sectional or period */
1.235     brouard  16855:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
1.360     brouard  16856:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each state\n\
                   16857: #  (these are weighted average of eij where weights are ");
1.227     brouard  16858:        if(vpopbased==1)
1.360     brouard  16859:          fprintf(ficrest,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally)\n in each health state (popbased=1) (mobilav=%d)\n",mobilav);
1.227     brouard  16860:        else
1.360     brouard  16861:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each state) \n");
                   16862:        fprintf(ficrest,"# with proportions of time spent in each state with standard error (on the right of the table.\n ");
1.335     brouard  16863:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  16864:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
1.360     brouard  16865:        for (i=1;i<=nlstate;i++) fprintf(ficrest," %% e.%d/e.. (std) ",i);
1.227     brouard  16866:        fprintf(ficrest,"\n");
                   16867:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  16868:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   16869:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  16870:        for(age=bage; age <=fage ;age++){
1.235     brouard  16871:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  16872:          if (vpopbased==1) {
                   16873:            if(mobilav ==0){
                   16874:              for(i=1; i<=nlstate;i++)
                   16875:                prlim[i][i]=probs[(int)age][i][k];
                   16876:            }else{ /* mobilav */ 
                   16877:              for(i=1; i<=nlstate;i++)
                   16878:                prlim[i][i]=mobaverage[(int)age][i][k];
                   16879:            }
                   16880:          }
1.219     brouard  16881:          
1.227     brouard  16882:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   16883:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   16884:          /* printf(" age %4.0f ",age); */
                   16885:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   16886:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   16887:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   16888:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   16889:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   16890:            }
1.361     brouard  16891:            epj[nlstate+1] +=epj[j]; /* epp=sum_j epj = sum_j sum_i w_i e_ij */
1.227     brouard  16892:          }
                   16893:          /* printf(" age %4.0f \n",age); */
1.219     brouard  16894:          
1.361     brouard  16895:          for(i=1, vepp=0.;i <=nlstate;i++)  /* Variance of total life expectancy e.. */
1.227     brouard  16896:            for(j=1;j <=nlstate;j++)
1.361     brouard  16897:              vepp += vareij[i][j][(int)age]; /* sum_i sum_j cov(e.i, e.j) = var(e..) */
1.227     brouard  16898:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
1.361     brouard  16899:          /* vareij[i][j] is the covariance  cov(e.i, e.j) and vareij[j][j] is the variance  of e.j  */
1.227     brouard  16900:          for(j=1;j <=nlstate;j++){
                   16901:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   16902:          }
1.360     brouard  16903:          /* And proportion of time spent in state j */
                   16904:          /* $$ E[r(X,Y)-E(r(X,Y))]^2=[\frac{1}{\mu_y} -\frac{\mu_x}{{\mu_y}^2}]' Var(X,Y)[\frac{1}{\mu_y} -\frac{\mu_x}{{\mu_y}^2}]$$ */
1.361     brouard  16905:           /* \frac{\mu_x^2}{\mu_y^2} ( \frac{\sigma^2_x}{\mu_x^2}-2\frac{\sigma_{xy}}{\mu_x\mu_y} +\frac{\sigma^2_y}{\mu_y^2}) */
                   16906:          /* \frac{e_{.i}^2}{e_{..}^2} ( \frac{\Var e_{.i}}{e_{.i}^2}-2\frac{\Var e_{.i} + \sum_{j\ne i} \Cov e_{.j},e_{.i}}{e_{.i}e_{..}} +\frac{\Var e_{..}}{e_{..}^2})*/
                   16907:          /*\mu_x = epj[j], \sigma^2_x = vareij[j][j][(int)age] and \mu_y=epj[nlstate+1], \sigma^2_y=vepp \sigmaxy= */
                   16908:          /* vareij[j][j][(int)age]/epj[nlstate+1]^2 + vepp/epj[nlstate+1]^4 */
1.360     brouard  16909:          for(j=1;j <=nlstate;j++){
                   16910:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[j]/epj[j]/epj[j]/epj[j] )); */
1.361     brouard  16911:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[j]/epj[j]/epj[j]/epj[j] )); */
                   16912:            
                   16913:            for(i=1,stdpercent=0.;i<=nlstate;i++){ /* Computing cov(e..,e.j)=cov(sum_i e.i,e.j)=sum_i cov(e.i, e.j) */
                   16914:              stdpercent += vareij[i][j][(int)age];
                   16915:            }
                   16916:            stdpercent= epj[j]*epj[j]/epj[nlstate+1]/epj[nlstate+1]* (vareij[j][j][(int)age]/epj[j]/epj[j]-2.*stdpercent/epj[j]/epj[nlstate+1]+ vepp/epj[nlstate+1]/epj[nlstate+1]);
                   16917:            /* stdpercent= epj[j]*epj[j]/epj[nlstate+1]/epj[nlstate+1]*(vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[nlstate+1]/epj[nlstate+1]); */ /* Without covariance */
                   16918:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[nlstate+1]/epj[nlstate+1] + epj[j]*epj[j]*vepp/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1] )); */
                   16919:            fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt(stdpercent));
1.360     brouard  16920:          }
1.227     brouard  16921:          fprintf(ficrest,"\n");
                   16922:        }
1.208     brouard  16923:       } /* End vpopbased */
1.269     brouard  16924:       free_vector(epj,1,nlstate+1);
1.208     brouard  16925:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   16926:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  16927:       printf("done selection\n");fflush(stdout);
                   16928:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  16929:       
1.335     brouard  16930:     } /* End k selection or end covariate selection for nres */
1.227     brouard  16931: 
                   16932:     printf("done State-specific expectancies\n");fflush(stdout);
                   16933:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   16934: 
1.335     brouard  16935:     /* variance-covariance of forward period prevalence */
1.269     brouard  16936:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16937: 
1.227     brouard  16938:     
1.290     brouard  16939:     free_vector(weight,firstobs,lastobs);
1.351     brouard  16940:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  16941:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  16942:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   16943:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   16944:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   16945:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  16946:     free_ivector(tab,1,NCOVMAX);
                   16947:     fclose(ficresstdeij);
                   16948:     fclose(ficrescveij);
                   16949:     fclose(ficresvij);
                   16950:     fclose(ficrest);
                   16951:     fclose(ficpar);
                   16952:     
                   16953:     
1.126     brouard  16954:     /*---------- End : free ----------------*/
1.219     brouard  16955:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  16956:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   16957:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  16958:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   16959:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  16960:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  16961:   /* endfree:*/
1.359     brouard  16962:   if(mle!=-3) free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
1.227     brouard  16963:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16964:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16965:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  16966:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   16967:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  16968:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   16969:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   16970:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  16971:   free_matrix(matcov,1,npar,1,npar);
                   16972:   free_matrix(hess,1,npar,1,npar);
                   16973:   /*free_vector(delti,1,npar);*/
                   16974:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   16975:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  16976:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  16977:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   16978:   
                   16979:   free_ivector(ncodemax,1,NCOVMAX);
                   16980:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   16981:   free_ivector(Dummy,-1,NCOVMAX);
                   16982:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  16983:   free_ivector(DummyV,-1,NCOVMAX);
                   16984:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  16985:   free_ivector(Typevar,-1,NCOVMAX);
                   16986:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  16987:   free_ivector(TvarsQ,1,NCOVMAX);
                   16988:   free_ivector(TvarsQind,1,NCOVMAX);
                   16989:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  16990:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  16991:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  16992:   free_ivector(TvarFD,1,NCOVMAX);
                   16993:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  16994:   free_ivector(TvarF,1,NCOVMAX);
                   16995:   free_ivector(TvarFind,1,NCOVMAX);
                   16996:   free_ivector(TvarV,1,NCOVMAX);
                   16997:   free_ivector(TvarVind,1,NCOVMAX);
                   16998:   free_ivector(TvarA,1,NCOVMAX);
                   16999:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  17000:   free_ivector(TvarFQ,1,NCOVMAX);
                   17001:   free_ivector(TvarFQind,1,NCOVMAX);
                   17002:   free_ivector(TvarVD,1,NCOVMAX);
                   17003:   free_ivector(TvarVDind,1,NCOVMAX);
                   17004:   free_ivector(TvarVQ,1,NCOVMAX);
                   17005:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  17006:   free_ivector(TvarAVVA,1,NCOVMAX);
                   17007:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   17008:   free_ivector(TvarVVA,1,NCOVMAX);
                   17009:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  17010:   free_ivector(TvarVV,1,NCOVMAX);
                   17011:   free_ivector(TvarVVind,1,NCOVMAX);
                   17012:   
1.230     brouard  17013:   free_ivector(Tvarsel,1,NCOVMAX);
                   17014:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  17015:   free_ivector(Tposprod,1,NCOVMAX);
                   17016:   free_ivector(Tprod,1,NCOVMAX);
                   17017:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  17018:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  17019:   free_ivector(Tage,1,NCOVMAX);
                   17020:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  17021:   free_ivector(TmodelInvind,1,NCOVMAX);
                   17022:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  17023: 
1.359     brouard  17024:   /* free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /\* Could be elsewhere ?*\/ */
1.332     brouard  17025: 
1.227     brouard  17026:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   17027:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  17028:   fflush(fichtm);
                   17029:   fflush(ficgp);
                   17030:   
1.227     brouard  17031:   
1.126     brouard  17032:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  17033:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   17034:     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  17035:   }else{
                   17036:     printf("End of Imach\n");
                   17037:     fprintf(ficlog,"End of Imach\n");
                   17038:   }
                   17039:   printf("See log file on %s\n",filelog);
                   17040:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  17041:   /*(void) gettimeofday(&end_time,&tzp);*/
                   17042:   rend_time = time(NULL);  
                   17043:   end_time = *localtime(&rend_time);
                   17044:   /* tml = *localtime(&end_time.tm_sec); */
                   17045:   strcpy(strtend,asctime(&end_time));
1.126     brouard  17046:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   17047:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  17048:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  17049:   
1.157     brouard  17050:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   17051:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   17052:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  17053:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   17054: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   17055:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17056:   fclose(fichtm);
                   17057:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17058:   fclose(fichtmcov);
                   17059:   fclose(ficgp);
                   17060:   fclose(ficlog);
                   17061:   /*------ End -----------*/
1.227     brouard  17062:   
1.281     brouard  17063: 
                   17064: /* Executes gnuplot */
1.227     brouard  17065:   
                   17066:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  17067: #ifdef WIN32
1.227     brouard  17068:   if (_chdir(pathcd) != 0)
                   17069:     printf("Can't move to directory %s!\n",path);
                   17070:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  17071: #else
1.227     brouard  17072:     if(chdir(pathcd) != 0)
                   17073:       printf("Can't move to directory %s!\n", path);
                   17074:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  17075: #endif 
1.126     brouard  17076:     printf("Current directory %s!\n",pathcd);
                   17077:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   17078:   sprintf(plotcmd,"gnuplot");
1.157     brouard  17079: #ifdef _WIN32
1.126     brouard  17080:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   17081: #endif
                   17082:   if(!stat(plotcmd,&info)){
1.158     brouard  17083:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17084:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  17085:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  17086:     }else
                   17087:       strcpy(pplotcmd,plotcmd);
1.157     brouard  17088: #ifdef __unix
1.126     brouard  17089:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   17090:     if(!stat(plotcmd,&info)){
1.158     brouard  17091:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17092:     }else
                   17093:       strcpy(pplotcmd,plotcmd);
                   17094: #endif
                   17095:   }else
                   17096:     strcpy(pplotcmd,plotcmd);
                   17097:   
                   17098:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  17099:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  17100:   strcpy(pplotcmd,plotcmd);
1.227     brouard  17101:   
1.126     brouard  17102:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  17103:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  17104:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  17105:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  17106:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  17107:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  17108:       strcpy(plotcmd,pplotcmd);
                   17109:     }
1.126     brouard  17110:   }
1.158     brouard  17111:   printf(" Successful, please wait...");
1.126     brouard  17112:   while (z[0] != 'q') {
                   17113:     /* chdir(path); */
1.154     brouard  17114:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  17115:     scanf("%s",z);
                   17116: /*     if (z[0] == 'c') system("./imach"); */
                   17117:     if (z[0] == 'e') {
1.158     brouard  17118: #ifdef __APPLE__
1.152     brouard  17119:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  17120: #elif __linux
                   17121:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  17122: #else
1.152     brouard  17123:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  17124: #endif
                   17125:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   17126:       system(pplotcmd);
1.126     brouard  17127:     }
                   17128:     else if (z[0] == 'g') system(plotcmd);
                   17129:     else if (z[0] == 'q') exit(0);
                   17130:   }
1.227     brouard  17131: end:
1.126     brouard  17132:   while (z[0] != 'q') {
1.195     brouard  17133:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  17134:     scanf("%s",z);
                   17135:   }
1.283     brouard  17136:   printf("End\n");
1.282     brouard  17137:   exit(0);
1.126     brouard  17138: }

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